【发布时间】:2016-06-08 18:32:12
【问题描述】:
我的计算机上同时运行 Python 2.7.10 和 Python 3.4.4。以下代码适用于 Python 2.7.10:
import urllib2
print urllib2.urlopen('http://google.com').read()
但是,如果我继续使用 Python 3.4.4 并运行
import urllib.request
print(urllib.request.urlopen('http://google.com').read())
我得到一对很长的错误:
Traceback (most recent call last):
File "C:\Python34\lib\urllib\request.py", line 1183, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "C:\Python34\lib\http\client.py", line 1137, in request
self._send_request(method, url, body, headers)
File "C:\Python34\lib\http\client.py", line 1182, in _send_request
self.endheaders(body)
File "C:\Python34\lib\http\client.py", line 1133, in endheaders
self._send_output(message_body)
File "C:\Python34\lib\http\client.py", line 963, in _send_output
self.send(msg)
File "C:\Python34\lib\http\client.py", line 898, in send
self.connect()
File "C:\Python34\lib\http\client.py", line 871, in connect
self.timeout, self.source_address)
File "C:\Python34\lib\socket.py", line 516, in create_connection
raise err
File "C:\Python34\lib\socket.py", line 507, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
print(urllib.request.urlopen('http://google.com').read())
File "C:\Python34\lib\urllib\request.py", line 161, in urlopen
return opener.open(url, data, timeout)
File "C:\Python34\lib\urllib\request.py", line 464, in open
response = self._open(req, data)
File "C:\Python34\lib\urllib\request.py", line 482, in _open
'_open', req)
File "C:\Python34\lib\urllib\request.py", line 442, in _call_chain
result = func(*args)
File "C:\Python34\lib\urllib\request.py", line 1211, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "C:\Python34\lib\urllib\request.py", line 1185, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
我已经明白,像这样的错误表示 Windows 设置有问题,建议 here(我正在运行 Windows 7),但我不明白它在 2.7 中的工作原理,而不是在 3.4 .
【问题讨论】:
-
以为他们改了包名...
-
建议:使用requests即可。
-
在 GNU/Linux 上使用 Python 3.2.3 可以正常工作。也许是 Windows 编译问题...
-
我在本地测试了这个(在 Windows 7;Python 3.5.0 上),它对我有用。
-
所以这不是python代码的问题,而是其他地方。我很想在这个项目中简单地使用 2.7,而不是试图追查问题,但我宁愿解决问题而不是避免它......