获取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
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /longerrorpage was not found on this server.</p>
<hr>
<address>Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80</address>
</body></html>


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


上一篇:静态库改为动态库后,可以影响到程序的执行结果


下一篇:shell重定向小记