在代理后使用urlopen时超时失败
在Linux下使用Python 2.7.3时,尝试使用超时参数时出现了奇怪的行为。
from urllib2 import urlopen, Request, HTTPError, URLError
url = "http://speedtest.website-solution.net/speedtest/random350x350.jpg"
try:
#f = urlopen(url, timeout=30) #never works - always times out
f = urlopen(url) #always works fine, returns after < 2 secs
print("opened")
f.close()
print("closed")
except IOError as e:
print(e)
pass
编辑:
深入研究后,发现问题似乎更底层……以下代码也有同样的问题:
s = socket.socket()
s.settimeout(30)
s.connect(("speedtest.website-solution.net", 80)) #times out
print("opened socket")
s.close()
它是在一个socks代理后面运行的。使用tsocks python test.py
来运行。想知道这是否会以某种方式影响套接字的超时?不过,timeout=None
正常工作,这点倒是很奇怪。
1 个回答
0
好的,我搞明白了。这确实和代理有关。我也不知道为什么,但下面的代码似乎解决了这个问题:
来源: https://code.google.com/p/socksipy-branch/
把这个放在代码的开头:
import urllib2
from urllib2 import urlopen, Request, HTTPError, URLError
import httplib
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.56.1", 101)
socks.wrapmodule(urllib2)
现在一切都正常了..