11

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,309
  • 3
  • 25
  • 46
Tampa
  • 62,379
  • 105
  • 250
  • 388

2 Answers2

12

Just take a step back:

result = urllib2.urlopen(request)
contents = result.read()
print result.getcode()
mdurant
  • 21,368
  • 2
  • 33
  • 59
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
  • 6,960
  • 9
  • 49
  • 67
  • 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. – frakman1 Aug 15 '20 at 15:29