【Python開發】urllib2.urlopen逾時問題__Python

來源:互聯網
上載者:User
原帖地址: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()
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.