【Python】 URLError: 错误

这几天用Python做爬虫的时候,总遇到python   URLError: 的异常,就是偶尔会出现,开的线程数越多,出现的频率就越大。 后来证明程序没有问题, 在网上查过资料,这个网络堵塞,多试几次就可以了。 

比如原代码是这样:

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:  All times is failed '
一般可以解决这个异常

你可能感兴趣的:(python,URL,异常)