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
2009-11-13 00:45:14
Note that getcode() was added in Python 2.6.
Mark
2009-11-13 00:52:47
@Mark, good point
Nadia Alramli
2009-11-13 00:54:37
+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
2009-11-13 00:46:01