Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python urllib2: Reading content body even during HTTPError exception?

Tags:

python

I'm using urllib2 to fetch a a page via HTTP. Sometimes the resource throws a HTTP error 400 (Bad Request) when my request contains an error. However, that response also contains an XML element that gives a detailed error message. It would be very handy to be able to see that error rather than just the HTTPError exception returned by urllib2.

How do I return the document contents in spite of the exception?

like image 917
jamieb Avatar asked Nov 02 '09 21:11

jamieb


1 Answers

import urllib2 try:     request = urllib2.Request('http://www.somesite.com')     response = urllib2.urlopen(req) except urllib2.HTTPError as e:     error_message = e.read()     print error_message 
like image 151
Tendayi Mawushe Avatar answered Sep 20 '22 01:09

Tendayi Mawushe