我之前在Windows XP计算机上安装了Python 2.6.2并运行以下代码:
import urllib2
import urllib
page = urllib2.Request('http://www.python.org/fish.html')
urllib2.urlopen( page )
我收到以下错误。
Traceback (most recent call last):<br>
File "C:\Python26\test3.py", line 6, in <module><br>
urllib2.urlopen( page )<br>
File "C:\Python26\lib\urllib2.py", line 124, in urlopen<br>
return _opener.open(url, data, timeout)<br>
File "C:\Python26\lib\urllib2.py", line 383, in open<br>
response = self._open(req, data)<br>
File "C:\Python26\lib\urllib2.py", line 401, in _open<br>
'_open', req)<br>
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain<br>
result = func(*args)<br>
File "C:\Python26\lib\urllib2.py", line 1130, in http_open<br>
return self.do_open(httplib.HTTPConnection, req)<br>
File "C:\Python26\lib\urllib2.py", line 1105, in do_open<br>
raise URLError(err)<br>
URLError: <urlopen error [Errno 11001] getaddrinfo failed><br><br><br>
答案 0 :(得分:4)
import urllib2
response = urllib2.urlopen('http://www.python.org/fish.html')
html = response.read()
你做错了。
答案 1 :(得分:3)
查看urllib2源代码,在traceback指定的行:
File "C:\Python26\lib\urllib2.py", line 1105, in do_open
raise URLError(err)
你会看到以下片段:
try:
h.request(req.get_method(), req.get_selector(), req.data, headers)
r = h.getresponse()
except socket.error, err: # XXX what error?
raise URLError(err)
因此,看起来源是套接字错误,而不是与HTTP协议相关的错误。可能的原因:你不在线,你是一个限制性防火墙,你的DNS已关闭,......
除此之外,正如mcandre所指出的那样,你的代码是错误的。
答案 2 :(得分:2)
名称解析错误。
getaddrinfo
用于解析请求中的主机名(python.org
)。如果失败,则表示无法解析名称,因为:
答案 3 :(得分:1)
Windows Vista,python 2.6.2
这是一个404页,对吗?
>>> import urllib2
>>> import urllib
>>>
>>> page = urllib2.Request('http://www.python.org/fish.html')
>>> urllib2.urlopen( page )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\urllib2.py", line 124, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python26\lib\urllib2.py", line 389, in open
response = meth(req, response)
File "C:\Python26\lib\urllib2.py", line 502, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python26\lib\urllib2.py", line 427, in error
return self._call_chain(*args)
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain
result = func(*args)
File "C:\Python26\lib\urllib2.py", line 510, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
>>>
答案 4 :(得分:0)
DJ
首先,我认为没有理由导入urllib;我只见过urllib2用于完全替换urllib,我知道没有任何功能从urllib中有用但是urllib2中缺少。
接下来,我注意到http://www.python.org/fish.html给了我404错误。 (这并不能解释你所看到的回溯/异常。我得到urllib2.HTTPError: HTTP Error 404: Not Found
通常,如果你只是想对网页进行默认提取(不添加特殊的HTTP标头,做任何类型的POST等),那么以下就足够了:
req = urllib2.urlopen('http://www.python.org/')
html = req.read()
# and req.close() if you want to be pedantic