urllib.urlopen 有效,但 urllib2.urlopen 无效 [英] urllib.urlopen works but urllib2.urlopen doesn't
问题描述
我有一个正在测试的简单网站.它在本地主机上运行,我可以在我的网络浏览器中访问它.索引页只是运行"这个词.urllib.urlopen
将成功读取页面,但 urllib2.urlopen
不会.这是一个演示问题的脚本(这是实际脚本,而不是其他测试脚本的简化):
I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". urllib.urlopen
will successfully read the page but urllib2.urlopen
will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):
import urllib, urllib2
print urllib.urlopen("http://127.0.0.1").read() # prints "running"
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception
这是堆栈跟踪:
Traceback (most recent call last):
File "urltest.py", line 5, in <module>
print urllib2.urlopen("http://127.0.0.1").read()
File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 412, in error
result = self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 575, in http_error_302
return self.parent.open(new)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 504: Gateway Timeout
有什么想法吗?我可能最终需要 urllib2
的一些更高级的功能,所以我不想只使用 urllib
,而且我想了解这个问题.
Any ideas? I might end up needing some of the more advanced features of urllib2
, so I don't want to just resort to using urllib
, plus I want to understand this problem.
推荐答案
听起来像是您定义了 urllib2 正在接受的代理设置.当它尝试代理127.0.0.01/"时,代理放弃并返回504错误.
Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy "127.0.0.01/", the proxy gives up and returns a 504 error.
proxy_support = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_support)
print opener.open("http://127.0.0.1").read()
# Optional - makes this opener default for urlopen etc.
urllib2.install_opener(opener)
print urllib2.urlopen("http://127.0.0.1").read()
这篇关于urllib.urlopen 有效,但 urllib2.urlopen 无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!