urllib2.urlopen超时未设置导致程序卡死 1、为urlopen设置可选参数 timeout 2、设置全局的socket超时: 3、使用定时器 timer

没有设置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()操作(下载内容)卡死,要解决这个问题方法有如下几个:
import urllib2
# http://classweb.loxa.com.tw/dino123/air/P1000772.jpg
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_urllib2
http://code.google.com/p/httplib2/wiki/Examples
http://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()