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

本文介绍了一种处理Python中使用urllib2模块请求网页时遇到的HTTP 404错误的方法。通过示例对比了错误和正确的处理方式,正确的处理能够详细输出错误的状态码、原因、请求URL及响应内容。
751

被折叠的 条评论
为什么被折叠?



