views:

525

answers:

2

How to get the code of the headers through urllib?

+9  A: 

The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.

>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
Nadia Alramli
Note that getcode() was added in Python 2.6.
Mark
@Mark, good point
Nadia Alramli
+8  A: 

You can use urllib2 as well:

import urllib2

req = urllib2.Request('http://www.python.org/fish.html')
try:
    resp = urllib2.urlopen(req)
except urllib2.URLError, e:
    if e.code == 404:
        # do something...
    else:
        # ...
else:
    # 200
    body = resp.read()
Joe Holloway