我正在抓取多个URL,以在其源代码中找到特定的关键字。但是,在搜寻一半的网站时,由于404或503之类的HTTP错误,我的蜘蛛突然停了下来。
我的搜寻器:
import urllib2
keyword = ['viewport']
with open('listofURLs.csv') as f:
for line in f:
strdomain = line.strip()
if strdomain:
req = urllib2.Request(strdomain.strip())
response = urllib2.urlopen(req)
html_content = response.read()
for searchstring in keyword:
if searchstring.lower() in str(html_content).lower():
print (strdomain, keyword, 'found')
f.close()
我应该添加什么代码来忽略带有HTTP错误的错误URL,并让搜寻器继续爬网?
最佳答案
您可以使用try-except块,如here所示。这使您可以将逻辑应用于有效的URL,并将不同的逻辑应用于产生HTTP错误的URL。
将链接中的解决方案应用于代码即可。
import urllib2
keyword = ['viewport']
with open('listofURLs.csv') as f:
for line in f:
strdomain = line.strip()
if strdomain:
req = urllib2.Request(strdomain.strip())
try:
response = urllib2.urlopen(req)
html_content = response.read()
for searchstring in keyword:
if searchstring.lower() in str(html_content).lower():
print (strdomain, keyword, 'found')
except urllib2.HTTPError, err:
# Do something here maybe print err.code
f.close()
这是您提供的代码的正确解决方案。但是,eLRuLL提出了一个很重要的观点,您确实应该考虑使用scrapy满足您的Web爬网需求。
关于python-2.7 - 如何在使用python 2.7抓取URL时忽略HTTP错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355790/