当前位置:  开发笔记 > 编程语言 > 正文

urllib.urlopen工作,但urllib2.urlopen没有

如何解决《urllib.urlopen工作,但urllib2.urlopen没有》经验,为你挑选了1个好方法。

我有一个我正在测试的简单网站.它在localhost上运行,我可以在我的Web浏览器中访问它.索引页面只是"运行"一词. urllib.urlopen将成功阅读该页面,但urllib2.urlopen不会.这是一个演示问题的脚本(这是实际的脚本而不是简化不同的测试脚本):

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 
    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,而且我想了解这个问题.



1> John Milliki..:

听起来你已经定义了urllib2正在接收的代理设置.当它尝试代理"127.0.0.01/"时,代理放弃并返回504错误.

来自Obscure python urllib2代理问题:

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()

推荐阅读
手机用户2502851955
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有