2013-05-13 48 views
0

我想创建一个脚本,查看文件,读取每行(这是url)并为我获取HTTP标题。 我有问题: 我尝试将结果重定向到文本文件,但无论如何,我尝试,它不工作。Python 3.3 - 获取标题并重定向结果

有人可以帮我用我的代码吗?

import urllib.request 
import sys 
open('sorti.txt','w') 
sorti = open("sorti.txt",'w') 
print('Creation de sorti.txt') 

text_file = open ("id.txt", "r") 
text_file.read().strip('\n') 
for lines in text_file: 
    urllib.request.urlopen('lines').write.sorti() 
    header = urllib.request.parse_http_list(lines).write.sorti() 
    sys.stdout(sorti) 
text_file.close 
sorti.close 
+0

你试过了吗?它工作? – Salem 2013-06-03 18:19:41

回答

0

假如您正在寻找这样的事情

URL1 
    header_1: value 
    ... 
    header_n: value 

    URL2 
    header_1: value 
    ... 
    header_n: value 

变化的代码如下:

text_file = open ("id.txt", "r") 
for line in text_file: 
    sorti.write(line) // writes the current url 
    obj = urllib.request.urlopen(line) 
    headers = dict(obj.info()) // gets the headers 
    for (h,v) in headers.items(): // write all with the specified format 
     sorti.write("{0}: {1}\n".format(h, v)) 
    sorti.write("\n") 
sorti.close 

那些write.sorti()将无法​​正常工作。