Python - Get Header information from URL

python, python-3.x

Solution

To get an HTTP response code in python-3.x, use the `urllib.request` module:

>>> import urllib.request
>>> response =  urllib.request.urlopen(url)
>>> response.getcode()
200
>>> if response.getcode() == 200:
...     print('Bingo')
... 
Bingo

The returned `HTTPResponse` Object will give you access to all of the headers, as well. For example:

>>> response.getheader('Server')
'Apache/2.2.16 (Debian)'

If the call to `urllib.request.urlopen()` fails, an `HTTPError` `Exception` is raised. You can handle this to get the response code:

import urllib.request
try:
    response = urllib.request.urlopen(url)
    if response.getcode() == 200:
        print('Bingo')
    else:
        print('The response code was not 200, but: {}'.format(
            response.get_code()))
except urllib.error.HTTPError as e:
    print('''An error occurred: {}
The response code was {}'''.format(e, e.getcode()))

Problem

I've been searching all around for a Python 3.x code sample to get HTTP Header information. Something as simple as get_headers equivalent in PHP cannot be found in Python easily. Or maybe I am not sure how to best wrap my head around it. In essence, I would like to code something where I can see whether a URL exists or not something in the line of ``` h = get_headers(url) if(h[0] == 200) { print("Bingo!") } ``` So far, I tried ``` h = http.client.HTTPResponse('http://docs.python.org/') ``` But always got an error

Original source