urllib2 urlopen 非常随机地工作 [英] urllib2 urlopen works very randomly

查看:26
本文介绍了urllib2 urlopen 非常随机地工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我从以下 url 获取 JSON 数据的这部分有时只能工作.有时它会返回 404 错误,并抱怨缺少 header 属性.如果我将其粘贴到 Web 浏览器上,它将在 100% 的时间内工作.所以我确定链接没有损坏或其他什么.

For some reasons this part where I fetch JSON data from following url will only works sometimes. And sometimes it will return 404 error, and complain about missing header attribute. It will work 100% of the time if I paste it onto a web browser. So I'm sure the link is not broken or something.

我在 Python 中遇到以下错误:

I get the following error in Python:

AttributeError: 'HTTPError' 对象没有属性 'header'

这是什么原因,可以修复吗?顺便说一句,我删除了 API 密钥,因为它是私有的.

What's the reason for this and can it be fixed? Btw I removed API key since it is private.

try:
    url = "http://api.themoviedb.org/3/search/person?api_key=API-KEY&query=natalie+portman"
    header = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16' }
    req = urllib2.Request(url, None, header)
    f = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e.code
    print e.msg
    print e.header
    print e.fp.read()

推荐答案

如文档所示 此处,您需要明确接受 JSON.只需在第一行之后添加第二行.

As is documented here, you need to explicitly accept JSON. Just add the second line after the first.

req = urllib2.Request(url, None, header)
req.add_header('Accept', 'application/json')

这篇关于urllib2 urlopen 非常随机地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆