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

简介: 错误方法: import urllib2req = urllib2.Request('http://127.0.0.1/longerrorpage')try: response=urllib2.

错误方法:

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://stackoverflow.com/questions/2233687/overriding-urllib2-httperror-and-reading-response-html-anyway


目录
相关文章
|
数据库
FastAPI(53)- Response Headers 响应设置 Headers
FastAPI(53)- Response Headers 响应设置 Headers
467 0
FastAPI(53)- Response Headers 响应设置 Headers
|
5月前
|
数据采集 存储
解决 urllib2 中 CookiesMiddleware 的 cookie 问题
解决 urllib2 中 CookiesMiddleware 的 cookie 问题
|
5月前
|
JSON 缓存 Java
修改Request与Response中的内容
修改Request与Response中的内容
50 0
|
存储
JavaWeb《三》Request请求转发与Response响应
javaweb的第三篇,介绍了Request请求转发与Response响应。
JavaWeb《三》Request请求转发与Response响应
|
前端开发 Python
urllib的一些使用案例
urllib的一些使用案例
107 0
|
数据采集 Python
爬虫第一次笔记 urllib的基本使用 urllib一个类型,六个方法 urllib下载 urllib请求对象的定制
爬虫第一次笔记 urllib的基本使用 urllib一个类型,六个方法 urllib下载 urllib请求对象的定制
87 0
爬虫第一次笔记 urllib的基本使用 urllib一个类型,六个方法 urllib下载 urllib请求对象的定制
Response完成重定向
Response完成重定向
57 0
Response完成重定向
|
JSON 安全 前端开发
跨域请求出现preflight request失败的问题的解决
# 问题出现 这两天在项目联调过程中突然前端同学报告出现CORS跨域问题无法访问。刚听到很奇怪,因为已经在项目里面设置了CORS规则,理论上不会出现这个问题。 ```java protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
50233 1