urllib2.HTTP Error:HTTP错误404:找不到有效的u

2024-04-23 23:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python opengraph库解析网站的opengraph标记https://github.com/erikriver/opengraph

import opengraph
url = 'http://www.foxnews.com/world/2014/10/20/uk-gun-owners-now-subject-to-warrantless-home-searches/'
og = opengraph.OpenGraph(url=url)
print og.to_json()

当我运行这个脚本时,我得到以下错误

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    raw = urllib2.urlopen(url)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found

urllib2用于在解析html之前获取它https://github.com/erikriver/opengraph/blob/master/opengraph/opengraph.py#L50-L52

为什么我会收到这个404错误?我可以从浏览器访问这个url,还可以使用这个php库https://github.com/scottmac/opengraph检索这个url的open graph标记。

python库能够检索所有其他url的open graph标记,但是这个url似乎是一个异常。


Tags: inpyhttps标记comhttpurlresponse
1条回答
网友
1楼 · 发布于 2024-04-23 23:29:29

更新时间:

您将得到一个404响应,因为您的请求未通过用户代理。 刚刚在virtualenv上安装了opengraph来测试它,它在header中添加了missing用户代理之后工作:

url = 'http://www.foxnews.com/world/2014/10/20/uk-gun-owners-now-subject-to-warrantless-home-searches/'
req = opengraph.opengraph.urllib2.Request(url, headers={ 'User-Agent': 'Mozilla/5.0' })
og = opengraph.OpenGraph()
og.parser(opengraph.opengraph.urllib2.urlopen(req).read())
og.to_json()

'{"site_name": "Fox News", "description": "Registered gun owners in the United Kingdom are now subject to unannounced visits to their homes under new guidance that allows police to inspect firearms storage without a warrant.", "title": "UK gun owners now subject to warrantless home searches", "url": "http://www.foxnews.com/world/2014/10/20/uk-gun-owners-now-subject-to-warrantless-home-searches/", "image": "http://global.fncstatic.com/static/v/all/img/fn_128x128.png", "scrape": false, "_url": null, "type": "article"}'

相关问题 更多 >