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
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.
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.
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.
Just take a step back:
result = urllib2.urlopen(request)
contents = result.read()
print result.getcode()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With