Its easy to print or get any HTTP response header after performing a request using urllib2 from Python. Using info() from response of urlopen(), you can easily print all headers. For example the below code. This will request to google.com, and will print all the headers that came as response.
The output will be
If you want to print only a single header from the response, you can do so. Let say you want to print only the header "Content-Type" from the response header. The code will be
And it will output as below on your screen.
import urllib2
req = urllib2.Request('http://www.google.com/')
res = urllib2.urlopen(req)
print res.info() ## printing the headers
res.close();
The output will be
Date: Sun, 02 Aug 2009 09:17:10 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=4...
Server: gws
Transfer-Encoding: chunked
Connection: close
If you want to print only a single header from the response, you can do so. Let say you want to print only the header "Content-Type" from the response header. The code will be
print res.info().get('Content-Type')
And it will output as below on your screen.
text/html; charset=ISO-8859-1
Comments