【发布时间】:2017-05-19 06:24:15
【问题描述】:
我在一个具有唯一 ID 的文本文件中有一百万个奇怪的 url 和搜索词。我需要打开网址并搜索搜索词,如果存在则表示为1 否则为0。
输入文件:
"ID" "URL","SearchTerm1","Searchterm2"
"1","www.google.com","a","b"
"2","www.yahoo.com","f","g"
"3","www.att.net","k"
"4" , "www.facebook.com","cs","ee"
代码片段:
import urllib2
import re
import csv
import datetime
from BeautifulSoup import BeautifulSoup
with open('txt.txt') as inputFile, open ('results.txt','w+') as proc_seqf:
header = 'Id' + '\t' + 'URL' + '\t'
for i in range(1,3):
header += 'Found_Search' + str(i) + '\t'
header += '\n'
proc_seqf.write(header)
for line in inputFile:
line=line.split(",")
url = 'http://' + line[1]
req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
html_content = urllib2.urlopen(req).read()
soup = BeautifulSoup(html_content)
if line[2][0:1] == '"' and line[2][-1:] == '"':
line[2] = line[2][1:-1]
matches = soup(text=re.compile(line[2]))
#print soup(text=re.compile(line[2]))
#print matches
if len(matches) == 0 or line[2].isspace() == True:
output_1 =0
else:
output_1 =1
#print output_1
#print line[2]
if line[3][0:1] == '"' and line[3][-1:] == '"':
line[3] = line[3][1:-1]
matches = soup(text=re.compile(line[3]))
if len(matches) == 0 or line[3].isspace() == True:
output_2 =0
else:
output_2 =1
#print output_2
#print line[3]
proc_seqf.write("{}\t{}\t{}\t{}\n".format(line[0],url,output_1, output_2))
输出文件:
ID,SearchTerm1,Searchterm2
1,0,1
2,1,0
3,0
4,1,1
代码有两个问题:
当我一次运行大约 200 个网址时,它给了我
urlopen error [Errno 11004] getaddrinfo failed error。有没有办法搜索紧密匹配但不完全匹配的内容?
【问题讨论】:
-
为什么不说明原因投反对票?
-
我怀疑关闭投票暗示了原因:太宽泛了。您在一篇文章中提出了三个问题,其中第二个问题确实属于 Code Review 而不是 Stack Overflow。
-
谢谢@Prune 对代码进行了更改。
-
你知道是什么URL导致urlopen失败吗?总是一样的吗?
-
它改变的不是一个固定的 url。
标签: python python-2.7 web-scraping