Reputation: 78422
How do I get status code in python 2.7 for urllib2? I dont want to use requests. I need urllib2.
request = urllib2.Request(url, headers=headers)
contents = urllib2.urlopen(request).read()
print request.getcode()
contents = json.loads(contents)
<type 'exceptions.AttributeError'>, AttributeError('getcode',), <traceback object at 0x7f6238792b48>
Thanks
Upvotes: 13
Views: 20818
Reputation: 8400
use getcode()
>>> import urllib
>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>>
for urllib2
try:
urllib2.urlopen('http://www.google.com/asdfsf')
except urllib2.HTTPError, e:
print e.code
will print
404
Upvotes: 6
Reputation: 28694
Just take a step back:
result = urllib2.urlopen(request)
contents = result.read()
print result.getcode()
Upvotes: 14