13

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

letsc
  • 2,515
  • 5
  • 35
  • 54
Tampa
  • 75,446
  • 119
  • 278
  • 425

2 Answers2

14

Just take a step back:

result = urllib2.urlopen(request)
contents = result.read()
print result.getcode()
mdurant
  • 27,272
  • 5
  • 45
  • 74
6

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
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
  • This answer assummes that the `urllib` method doesn't throw an exception. But it does. I tried to open a url that returns error code 401 (Unauthorized) and it threw an exception on the `urlopen` call. – Frak Aug 15 '20 at 15:29