Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get status code for urllib2 in python 2.7

Tags:

python

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

like image 922
Tampa Avatar asked Mar 12 '15 17:03

Tampa


People also ask

How do I use urllib2 in Python?

urllib2 offers a very simple interface, in the form of the urlopen function. Just pass the URL to urlopen() to get a “file-like” handle to the remote data. like basic authentication, cookies, proxies and so on. These are provided by objects called handlers and openers.

How do I fix No module named urllib2?

The Python "ModuleNotFoundError: No module named 'urllib2'" occurs because the urllib2 module has been split into urllib. request and urllib. response in Python 3. To solve the error, import the module as from urllib.

Is Urllib included in Python 3?

The urllib module in Python 3 allows you access websites via your program. This opens up as many doors for your programs as the internet opens up for you. urllib in Python 3 is slightly different than urllib2 in Python 2, but they are mostly the same.


1 Answers

Just take a step back:

result = urllib2.urlopen(request)
contents = result.read()
print result.getcode()
like image 128
mdurant Avatar answered Sep 28 '22 01:09

mdurant