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

11

我尝试使用以下代码从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

请求帮忙,提前致谢。


9
这不是错误,而是预期的响应对象。你可能需要更详细地阅读文档。 - Martijn Pieters
2个回答

22

你没有收到错误信息,而是得到了一个预期的响应对象。如果你想要访问响应数据,那么你需要从该对象中读取,或者检查标题和状态码。

读取响应正文数据就像这样简单:

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

根据urllib.request.urlopen()文档

对于http和https的url,此函数返回一个http.client.HTTPResponse对象,该对象具有以下HTTPResponse对象方法。

在上面我使用了HTTPResponse.read()方法

请注意,结果将是编码字节,如果你需要文本,你仍然需要解码。你调用的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'之类的键。


谢谢。现在我的输出中包含了字节文字。b'<myoutput>' - Nitesh Ash

2

如果您只需要基本的命令行HTTP客户端功能,例如curl或wget(流行的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)

如果你想要字节对象,只需删除 .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等)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接