当站点还发出HTTP错误时,如何访问xml响应

2024-09-23 22:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

以下url返回浏览器中的预期响应: http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=notonfile99&api_key=8e9de6bd545880f19d2d2032c28992b4

<lfm status="failed">
<error code="6">No user with that name was found</error>
</lfm>

但我无法通过以下代码访问Python中的xml,因为引发了HTTPError异常: “由于HTTP错误400:错误请求”

import urllib
urlopen('http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=notonfile99&api_key=8e9de6bd545880f19d2d2032c28992b4')

我发现我可以通过使用urlretrieve而不是urlopen来找到这个,但是html响应会被写入disc。你知道吗

有没有一种方法,只要使用pythonv2.7标准库,我就可以获得xml响应,而不必从光盘中读取它,并执行内务管理?你知道吗

我看到以前在PHP上下文中有人问过这个问题,但我不知道如何将答案应用于Python: DOMDocument load on a page returning 400 Bad Request status


Tags: keycomapihttpwsstatus错误error
1条回答
网友
1楼 · 发布于 2024-09-23 22:24:26

从这里复制:http://www.voidspace.org.uk/python/articles/urllib2.shtml#httperror

引发的异常包含错误页的全文:

#!/usr/bin/python2

import urllib2

try:
    resp = urllib2.urlopen('http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=notonfile99&api_key=8e9de6bd545880f19d2d2032c28992b4')
except urllib2.HTTPError, e:
    print e.code
    print e.read()

相关问题 更多 >