urlopen在Python 2.7中工作,但在Python 3.4中失败

时间:2016-06-08 18:32:12

标签: python windows urlopen

我的计算机上运行了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>

我已经明白,像这样的错误代表了建议here(我正在运行Windows 7)的Windows设置问题,但我无法理解的是它在2.7中是如何工作的而不是在3.4。

1 个答案:

答案 0 :(得分:0)

在解决方案之后,Python 2.7代码开始抛出相同的错误。出于沮丧,我开始应用microscoft修复。我开始注销并重新登录。一切都按预期工作......