如何在Python 3中处理urllib的超时?
如何在Python 3中处理urllib的超时?
首先,我的问题与这个问题非常相似。我希望urllib.urlopen()的超时能够引发一个我可以处理的异常。
这难道不属于URLError吗?
try: response = urllib.request.urlopen(url, timeout=10).read().decode('utf-8') except (HTTPError, URLError) as error: logging.error( '无法获取%s的数据,因为%s\nURL:%s', name, error, url) else: logging.info('访问成功。')
错误信息:
resp = urllib.request.urlopen(req, timeout=10).read().decode('utf-8')
File "/usr/lib/python3.2/urllib/request.py", line 138, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.2/urllib/request.py", line 369, in open
response = self._open(req, data)
File "/usr/lib/python3.2/urllib/request.py", line 387, in _open
'_open', req)
File "/usr/lib/python3.2/urllib/request.py", line 347, in _call_chain
result = func(*args)
File "/usr/lib/python3.2/urllib/request.py", line 1156, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "/usr/lib/python3.2/urllib/request.py", line 1141, in do_open
r = h.getresponse()
File "/usr/lib/python3.2/http/client.py", line 1046, in getresponse
response.begin()
File "/usr/lib/python3.2/http/client.py", line 346, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.2/http/client.py", line 308, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.2/socket.py", line 276, in readinto
return self._sock.recv_into(b)
socket.timeout: 超时
在Python 3中,对urllib
和urllib2
模块进行了重组,合并为urllib
。可能是这个变化导致了这个问题吗?