urllib2.urlopen超時問題

原帖地址: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
r = 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 333333333333333333
except Exception,e:
        print "444444444444444444---------" + str(e)

print "55555555555555"

2、設置全局的socket超時:

import socket
socket.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 urlopen
from threading import Timer
url = "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()


轉載自 :http://blog.csdn.net/waterforest_pang/article/details/16885259

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章