6

为什么这个简单的 Python 代码不起作用?

import urllib
file = urllib.urlopen('http://www.google.com')
print file.read()

这是我得到的错误:

Traceback (most recent call last):
  File "C:\workspace\GarchUpdate\src\Practice.py", line 26, in <module>
    file = urllib.urlopen('http://www.google.com')
  File "C:\Python26\lib\urllib.py", line 87, in urlopen
    return opener.open(url)
  File "C:\Python26\lib\urllib.py", line 206, in open
    return getattr(self, name)(url)
  File "C:\Python26\lib\urllib.py", line 345, in open_http
    h.endheaders()
  File "C:\Python26\lib\httplib.py", line 892, in endheaders
    self._send_output()
  File "C:\Python26\lib\httplib.py", line 764, in _send_output
    self.send(msg)
  File "C:\Python26\lib\httplib.py", line 723, in send
    self.connect()
  File "C:\Python26\lib\httplib.py", line 704, in connect
    self.timeout)
  File "C:\Python26\lib\socket.py", line 514, in create_connection
    raise error, msg
IOError: [Errno socket error] [Errno 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

我已经尝试了几个不同的页面,但我永远无法urlopen正确执行该方法。

4

5 回答 5

4

您的代码不是这里的问题。

您的 IE 中是否有任何代理设置?

这说明了 urllib.urlopen 的 python 文档:

在 Windows 环境中,如果未设置代理环境变量,
则从注册表的 Internet 设置
部分获取代理设置。

于 2010-05-27T18:23:52.960 回答
3

如果可以更改某些代码行,请尝试使用 urllib2。以秒为单位设置超时参数

例如:

urllib2.urlopen(http://www.abc.com/api, timeout=20)

在这里,连接会持续更长的时间。因此,例如,如果您正在读取一个太大的 XML 文件,它可以避免不完整的读取。

如果网络连接缓慢或突然中断,上述代码将永远无法工作。

于 2014-03-04T06:00:27.867 回答
1

如果您有wireshark,请检查发送的内容以及是否有任何返回。如果您可以看到正在发送的 GET 请求,它将帮助您调试问题。

我还记得曾经遇到过类似的问题,我所做的是刷新我的 dns 缓存

(ipconfig /flushdns) 并重新启动。它解决了我的问题。我猜尝试它并没有什么坏处。

于 2010-05-27T19:39:26.367 回答
0

对于蟒蛇 3:

import urllib.request

proxies=urllib.request.ProxyHandler({'http':None})

opener=urllib.request.build_opener(proxies)

urllib.request.install_opener(opener)

j=urllib.request.urlopen(url="https://google.com")

k=j.read()

print(k)
于 2018-10-21T15:34:31.653 回答
0

你的代码是正确的

import urllib
file = urllib.urlopen('http://www.google.com')
print file.read()

但很可能您的互联网有问题,或者您没有正确设置 dns。

您可以使用 urllib 的请求库。

于 2021-07-11T07:39:51.027 回答