获取urllib2.urlopen失败时的错误页面

错误方法:

import urllib2
req = urllib2.Request('http://127.0.0.1/longerrorpage')
try:
    response=urllib2.urlopen(req)
except Exception,e:
    print e, response.read()

HTTP Error 404: Not Found
正确方法:

import urllib2
req = urllib2.Request('http://127.0.0.1/longerrorpage')
try:
    response=urllib2.urlopen(req)
except urllib2.HTTPError,e:
    print e.code
    print e.reason
    print e.geturl()
    print e.read()
404
Not Found
http://127.0.0.1/longerrorpage


404 Not Found

Not Found

The requested URL /longerrorpage was not found on this server.


Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80


参考:http://stackoverflow.com/questions/2233687/overriding-urllib2-httperror-and-reading-response-html-anyway


你可能感兴趣的:(网络,python)