python - urllib.urlopen 有效,但 urllib2.urlopen 无效

标签 python urllib2 urllib

我有一个正在测试的简单网站。它在本地主机上运行,​​我可以在我的网络浏览器中访问它。索引页就是简单的“运行”二字。 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 <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,而且我想了解这个问题。

最佳答案

听起来您定义了 urllib2 正在使用的代理设置。当它尝试代理“127.0.0.01/”时,代理放弃并返回 504 错误。

来自 Obscure python urllib2 proxy gotcha :

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

关于python - urllib.urlopen 有效,但 urllib2.urlopen 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/201515/

相关文章:

python - 避免在 Python Urlopen 中下载文件

python - 什么是全局默认超时

python - itertools.groupby() 生成的迭代器被意外消耗

python - dataframe KeyError,虽然它存在

python - 如何使用 youtube data api 检查 Creativecommons 视频?我有以下代码,如果视频是知识共享,如何打印 true?

python - 使用请求获取 .onion 域

python - 带有 urllib2 的代理

python - python 的注释(例如数据类)可以扩展到它生成的代码中吗?

python - 使用许多同时请求(如 ab)对 Django 应用程序进行基准测试

python-3.x - ubuntu、python、ssl.SSLError : [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl. c:852)