1. 程式人生 > >Python爬蟲--timeout設定--防止訪問時間過長造成假死

Python爬蟲--timeout設定--防止訪問時間過長造成假死

爬蟲有時候會因為爬去某些網頁速度極慢,影響效能。所有可以設定超時時間。
timeout單位秒
設定超時時間為0,使用try語句。

#coding:utf-8
**urllib2**
超時可以通過 urllib2.urlopen() 的 timeout 引數直接設定。
例如:
#coding:utf-8
import urllib2
try:
    url = "http://www.baidu.com"
    f = urllib2.urlopen(url, timeout=0) #timeout設定超時的時間
    result = f.read()
    print result
except
Exception,e: print 'a',str(e)

輸出異常:

a <urlopen error timed out>

timeout設定為一之後就能正常返回獲取的html程式碼了。