原帖地址:http://hi.baidu.com/yss1983/item/933fbe45a09c43e01381da06
問題描述: 沒有設定timeout參數,結果在網路環境不好的情況下,時常出現read()方法沒有任何反應的問題,程式卡死在read()方法裡,搞了大半天,才找到問題,給urlopen加上timeout就ok了,設定了timeout之後逾時之後read逾時的時候會拋出socket.timeout異常,想要程式穩定,還需要給urlopen加上異常處理,再加上出現異常重試,程式就完美了。 import urllib2 url='http://www.facebook.com/' fails = 0 while True: try: if fails >= 20: break req = urllib2.Request(url) response = urllib2.urlopen(req, None, 3) page = response.read() except: fails += 1 print '網路連接出現問題, 正在嘗試再次請求: ', fails else: break
解決方案:
有時候我們在爬取網路資料時,會因為對方網速緩慢、伺服器逾時等原因, 導致 urllib2.urlopen() 之後的 read()操作(下載內容)卡死,要解決這個問題方法有如下幾個: 1、為urlopen設定選擇性參數 timeout
import urllib2# http://classweb.loxa.com.tw/dino123/air/P1000772.jpgr = urllib2.Request("http://classweb.loxa.com.tw/dino123/air/P1000775.jpg")try: print 111111111111111111 f = urllib2.urlopen(r, data=None, timeout=3) print 2222222222222222 result = f.read() print 333333333333333333except Exception,e: print "444444444444444444---------" + str(e)print "55555555555555"
2、設定全域的socket逾時:
import socketsocket.setdefaulttimeout(10.0) 或者使用:httplib2 or timeout_urllib2http://code.google.com/p/httplib2/wiki/Exampleshttp://code.google.com/p/timeout-urllib2/source/browse/trunk/timeout_urllib2.py
3、使用定時器 timer
from urllib2 import urlopenfrom threading import Timerurl = "http://www.python.org"def handler(fh): fh.close()fh = urlopen(url)t = Timer(20.0, handler,[fh])t.start()data = fh.read() #如果二進位檔案需要換成二進位的讀取方式t.cancel()