Urllib2 urlopen is very messy

For some reason, this part where I get the JSON data from the following url will only work sometimes. And sometimes it returns a 404 error and complains about the missing title attribute. It will work 100% of the time if I paste it into a web browser. So I'm pretty sure the link isn't broken or something.

I am getting the following error in Python:

AttributeError: 'HTTPError' object has no attribute 'header'

What is the reason for this and can be corrected? Btw I deleted my API key since it is private.

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



source to share

1 answer

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

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




All Articles