如何克服Python http.client.HTTPResponse对象?

2024-05-11 21:00:19 发布

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

我试图从以下代码的url获取响应。 我正在使用Python 3.x

from urllib.request import urlopen

url_getallfolders = 'https://qa.wittyparrot.com/alfresco/service/acrowit/userfolderinfo?access_token=TICKET_83361146b0e140f48ba404c3d8457452a92e117f'
x = urlopen(url_getallfolders)
print(x)

我得到以下错误:

<http.client.HTTPResponse object at 0x030304B0>

我甚至试过urllib.urlopen:

x = urllib.urlopen(url_getallfolders)
print(x)

然后我得到这个错误:

NameError: name 'urllib' is not defined

请帮忙。提前谢谢


Tags: 代码fromhttpsimportcomurlrequest错误
2条回答

您没有得到错误,而是得到了预期的响应对象。如果要从响应访问数据,则需要从该对象中读取,或者检查头和状态代码。

读取响应体数据非常简单:

x = urlopen(url_getallfolders)
data = x.read()

^{} documentation

For http and https urls, this function returns a http.client.HTTPResponse object which has the following HTTPResponse Objects methods.

在这里我使用了上面的^{} method

请注意,结果将是编码字节,如果您需要文本,则仍需要解码该文本。您调用的URL返回JSON,因此您可能希望将其解码为Python:

import json

x = urlopen(url_getallfolders)
raw_data = x.read()
encoding = x.info().get_content_charset('utf8')  # JSON default
data = json.loads(raw_data.decode(encoding))

之后,您可以访问诸如'error''errorList''respList''warning'等键。

如果您只需要超级基本的面向命令行的HTTP客户端功能,例如curlwget(流行的CLI实用程序),而不需要任何选项;在这里,您为它提供一个URL,它只返回纯文本和HTML:

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from urllib.request import urlopen

with urlopen('https://example.com') as x:
     data = x.read().decode('utf-8')

print(data)

如果需要byte对象,只需删除.decode('utf-8'),这样看起来:

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from urllib.request import urlopen

with urlopen('https://example.com') as x:
     data = x.read()

print(data)

我试着把它减少到尽可能少的行。可以单独定义变量(url等)。

相关问题 更多 >