簡體   English   中英

urlopen在Python 2.7中有效,但在Python 3.4中失敗

[英]urlopen works in Python 2.7 but fails in Python 3.4

我的計算機上同時運行了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設置存在問題(我正在運行Windows 7),但是我無法理解的是它在2.7中的工作原理,而不是在3.4中的工作原理。

在解決方案上工作之后,Python 2.7代碼開始引發相同的錯誤。 出於沮喪,我開始使用microscoft修復程序。 我先注銷然后重新登錄。 現在一切都按預期進行...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM