【问题标题】:urllib2.urlopen() vs urllib.urlopen() - urllib2 throws 404 while urllib works! WHY?urllib2.urlopen() 与 urllib.urlopen() - urllib2 在 urllib 工作时抛出 404!为什么?
【发布时间】:2010-12-29 03:53:06
【问题描述】:
import urllib

print urllib.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read()

上述脚本工作并返回预期结果,同时:

import urllib2

print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read()

抛出以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/urllib2.py", line 124, in urlopen
    return _opener.open(url, data)
  File "/usr/lib/python2.5/urllib2.py", line 387, in open
    response = meth(req, response)
  File "/usr/lib/python2.5/urllib2.py", line 498, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.5/urllib2.py", line 425, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.5/urllib2.py", line 506, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found

有人知道这是为什么吗?我是从我的家庭网络上的笔记本电脑上运行这个的,没有代理设置 - 只是直接从我的笔记本电脑到路由器,然后到 www。

【问题讨论】:

    标签: python url http-status-code-404 urllib2 urllib


    【解决方案1】:

    该 URL 确实会导致 404,但包含大量 HTML 内容。 urllib2 正在(正确地)将其作为错误条件进行处理。您可以像这样恢复该网站的 404 页面的内容:

    import urllib2
    try:
        print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read()
    except urllib2.HTTPError, e:
        print e.code
        print e.msg
        print e.headers
        print e.fp.read()
    

    【讨论】:

    • 很高兴知道 - 出于好奇,当我在浏览器中输入此 URL 时,它也可以工作。这是否意味着浏览器也收到了 404 但只是像 urllib 一样显示内容?
    • @Jerry 是的,就是这个意思。您可以使用 Firebug 或 Safari/Chrome 的 Web Inspector 验证这一点。
    • 我有萤火虫,我已经检查过了,但我没有看到任何表明 404 的东西 - 你有什么特别的事情要做吗?出于病态的好奇,为什么浏览器会容忍如此糟糕的标准?为什么不直接指出它找不到文件呢?这是它用来阻止机器人的网站的某种技巧吗 - 返回一个 404 内容,知道浏览器会显示内容并且大多数机器人会继续前进?
    • 我认为它返回 404 是因为他们的网站存在错误。 404 可以包含您想要的任何内容。例如,合法的 404 可能会返回站点目录或与您键入的 URL 相关的文本搜索结果。浏览器正在做他们应该做的事情。
    猜你喜欢
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多