错误方法:
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>