Finding web host headers

Tim Chase python.list at tim.thechases.com
Thu Jun 1 13:08:27 EDT 2006


> Is there any way to fetch a website's host/version headers using
> Python?

 >>> import httplib
 >>> conn = httplib.HTTPConnection("docs.python.org")
 >>> conn.connect()
 >>> conn.request("HEAD", "/")
 >>> response = dict([(k.lower(), v) for k,v in conn.getresponse()])
 >>> conn.close()
 >>> server = response["server"]
 >>> print server
Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 
Python/2.3.5 mod_ssl/2.0.54 OpenSSL/0.9.7e


I've found a bit of discrepancy with regards to the case of the 
"server" portion, so the above code just normalizes it to 
lowercase and then shoves it in a dictionary.

You can then do as you please with the contents of the "server" 
variable.

It's theoretically possible that the server can return differing 
headers based on the URL you request or its method.  You'll have 
to adjust the request() call for the method (GET/HEAD/POST, etc) 
and for the resource you want (in this case, just "/")

-tkc






More information about the Python-list mailing list