这几天用Python做爬虫的时候,总遇到python URLError: <urlopen error timed out> 的异常,就是偶尔会出现,开的线程数越多,出现的频率就越大。 后来证明程序没有问题, 在网上查过资料,这个网络堵塞,多试几次就可以了。
比如原代码是这样:
if headers:
req=urllib2.Request(url,headers=headers)
else :
req=urllib2.Request(url)
opener=urllib2.build_opener(cookieproc)
urllib2.install_opener(opener)
page=urllib2.urlopen(req,timeout=5).read()改了之后加一个循环即可:
if headers:
req=urllib2.Request(url,headers=headers)
else :
req=urllib2.Request(url)
opener=urllib2.build_opener(cookieproc)
urllib2.install_opener(opener)
global Max_Num
Max_Num=6
for i in range(Max_Num):
try:
page=urllib2.urlopen(req,timeout=5).read()
break
except:
if i < Max_Num-1:
continue
else :
print 'URLError: <urlopen error timed out> All times is failed '一般可以解决这个异常
本文介绍了一种解决Python爬虫中出现URLError: <urlopenerrortimedout>异常的方法,通过增加重试机制来提高爬取成功率。
2万+

被折叠的 条评论
为什么被折叠?



