如何克服Python http.client.HTTPResponse对象?
我已经尝试从url获取响应,来自以下代码。 我正在使用Python3.x如何克服Python http.client.HTTPResponse对象?,python,urllib,python-3.4,Python,Urllib,Python 3.4,我已经尝试从url获取响应,来自以下代码。 我正在使用Python3.x from urllib.request import urlopen url_getallfolders = 'https://qa.wittyparrot.com/alfresco/service/acrowit/userfolderinfo?access_token=TICKET_83361146b0e140f48ba404c3d8457452a92e117f' x = urlopen(url_getallfolde
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>
然后我得到这个错误:
NameError: name 'urllib' is not defined
请帮忙。提前感谢您没有收到错误,而是收到了预期的响应对象。如果您想从响应中访问数据,那么您需要从该对象读取数据,或者检查标题和状态代码 读取响应主体数据非常简单,如下所示:
x = urlopen(url_getallfolders)
data = x.read()
从:
对于http和https URL,此函数返回具有以下方法的http.client.HTTPResponse
对象
我在那里用的是上面的
请注意,结果将是编码字节,如果您需要文本,则仍然需要对该文本进行解码。您调用的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'
,您没有收到错误,而是得到了预期的响应对象。如果您想从响应中访问数据,那么您需要从该对象读取数据,或者检查标题和状态代码
读取响应主体数据非常简单,如下所示:
x = urlopen(url_getallfolders)
data = x.read()
从:
对于http和https URL,此函数返回具有以下方法的http.client.HTTPResponse
对象
我在那里用的是上面的
请注意,结果将是编码字节,如果您需要文本,则仍然需要对该文本进行解码。您调用的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))
之后,如果您只需要面向超基本命令行的HTTP客户端功能,如
curl
或wget
(流行的CLI实用程序),则可以访问键,如'error'
,'errorList'
,'respList'
和'warning'
,而无需任何选项;您向其提供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等)。如果您只需要面向超基本命令行的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等)。这不是错误。它是预期的响应对象。您可能想更详细地阅读文档。这不是错误。它是预期的响应对象。您可能想更详细地阅读文档。谢谢。现在我得到了字节文本和输出。谢谢。现在我得到了字节文字和输出。b'