設定 http 或 socket 通路逾時,來防止爬蟲抓取某個頁面時間過長。
pycurl 庫的調用中,可以設定逾時時間:
c.setopt(pycurl.connecttimeout, 60)
在 python 2.6 版本下,httplib 庫由于有如下構造函數:
class httpconnection:
def __init__(self, host, port=none, strict=none,
timeout=socket._global_default_timeout):
self.timeout = timeout
是以可以設定:
如果通過 httpconnection 或 httpsconnection 的構造函數給定逾時時間,那麼阻塞操作(如試圖建立連接配接)将會逾時。如果沒有給或者指派 none ,那麼它将使用全局的逾時時間設定。
python 2.5 下,因為 httpconnection 類的 __init__ 函數沒有 timeout 參數,是以通過一個隐藏很深的函數:
httplib.socket.setdefaulttimeout(3)#輸入參數機關貌似是分鐘
來設定逾時。
最後,抓取時如果實在找不到什麼函數能設定逾時時間,那麼可以設定全局的 socket 逾時,雖然這樣做不大合适:
>>> import socket
>>> socket.setdefaulttimeout(90)
from urllib2 import urlopen
import socket
slowurl =”http://www.wenxuecity.com/”
socket.setdefaulttimeout(1)
try:
data = urlopen(slowurl)
data.read()
except socket.error:
errno, errstr = sys.exc_info()[:2]
if errno == socket.timeout:
print "there was a timeout"
else:
print "there was some other socket error"