72

我收到“HTTP 错误 500:内部服务器错误”响应,但我仍想读取错误 HTML 中的数据。

使用 Python 2.6,我通常使用以下方法获取页面:

import urllib2
url = "http://google.com"
data = urllib2.urlopen(url)
data = data.read()

当尝试在失败的 URL 上使用它时,我得到了异常urllib2.HTTPError

urllib2.HTTPError: HTTP Error 500: Internal Server Error

如何urllib2在它们返回内部服务器错误的同时获取此类错误页面(有或没有)?

请注意,对于 Python 3,相应的例外是urllib.error.HTTPError.

4

3 回答 3

136

是一个类似HTTPError 文件的对象。你可以捕捉它,然后捕捉它read的内容。

try:
    resp = urllib2.urlopen(url)
    contents = resp.read()
except urllib2.HTTPError, error:
    contents = error.read()
于 2010-02-10T01:18:53.647 回答
9

如果您的意思是要阅读 500 的正文:

request = urllib2.Request(url, data, headers)
try:
        resp = urllib2.urlopen(request)
        print resp.read()
except urllib2.HTTPError, error:
        print "ERROR: ", error.read()

在您的情况下,您不需要建立请求。做就是了

try:
        resp = urllib2.urlopen(url)
        print resp.read()
except urllib2.HTTPError, error:
        print "ERROR: ", error.read()

所以,你不要覆盖 urllib2.HTTPError,你只需处理异常。

于 2010-02-10T00:59:42.483 回答
-1
alist=['http://someurl.com']

def testUrl():
    errList=[]
    for URL in alist:
        try:
            urllib2.urlopen(URL)
        except urllib2.URLError, err:
            (err.reason != 200)
            errList.append(URL+" "+str(err.reason))
            return URL+" "+str(err.reason)
    return "".join(errList)

testUrl()
于 2016-04-10T11:40:07.727 回答