How to get HTTP return code from python urllib's urlopen?

diemacht picture diemacht · Feb 10, 2013 · Viewed 10k times · Source

I have the following code:

f = urllib.urlopen(url)
html = f.read()

I would like to know the HTTP status code (HTTP 200, 404 etc) that comes from opening the url above.

Anybody knows how it can be done?

P.S. I use python 2.5.

Thanks!!!

Answer

Forhad Ahmed picture Forhad Ahmed · Feb 10, 2013

You can use the .getcode() method of the object returned by urlopen()

url = urllib.urlopen('http://www.stackoverflow.com/')
code = url.getcode()