如何读取来自 Python 请求的响应?

我有两个 Python 脚本,一个使用 Urllib2图书馆,一个使用 请求库

我发现 Request 更容易实现,但是我找不到 urlib2的 read()函数的等价物。例如:

...
response = url.urlopen(req)
print response.geturl()
print response.getcode()
data = response.read()
print data

一旦我建立了我的文章的网址,data = response.read()给我的内容-我试图连接到一个 vcloud 总监 api 实例和响应显示我可以访问的端点。但是,如果我按照以下方式使用请求库... ..。

....


def post_call(username, org, password, key, secret):


endpoint = '<URL ENDPOINT>'
post_url = endpoint + 'sessions'
get_url = endpoint + 'org'
headers = {'Accept':'application/*+xml;version=5.1', \
'Authorization':'Basic  '+ base64.b64encode(username + "@" + org + ":" + password), \
'x-id-sec':base64.b64encode(key + ":" + secret)}
print headers
post_call = requests.post(post_url, data=None, headers = headers)
print post_call, "POST call"
print post_call.text, "TEXT"
print post_call.content, "CONTENT"
post_call.status_code, "STATUS CODE"


....

... . print post_call.textprint post_call.content不返回任何内容,即使请求后呼叫的状态码等于200。

为什么“请求”的响应没有返回任何文本或内容?

539437 次浏览

请求没有相当于 Urlib2的 read()

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

看起来您正在发出的 POST 请求没有返回任何内容。POST 请求通常是这种情况。也许它放了一块饼干?状态代码告诉您 POST 最终还是成功了。

Python 3的编辑:

Python 现在以不同的方式处理数据类型 response.content返回一个 bytes序列(表示 ASCII 的整数) ,而 response.text是一个 string序列(字符序列)。

因此,

>>> print response.content == response.text
False


>>> print str(response.content) == response.text
True

如果响应是在 json 中,您可以执行如下操作(python3) :

import json
import requests as reqs


# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')


# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)


for i in response_dict:
print("key: ", i, "val: ", response_dict[i])

要查看响应中的所有内容,可以使用 .__dict__:

print(response.__dict__)

如果你推送,例如图像,到一些 API,并希望结果地址(响应)回来,你可以这样做:

import requests
url = 'https://uguu.se/api.php?d=upload-tool'
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response = requests.post(url, data=data, files=files)
current_url = response.text
print(response.text)

如果响应在 Json,你可以直接在 Python 3中使用下面的方法,不需要使用 json importjson.loads()方法:

response.json()

有三种不同的方法可以让你得到你所得到的回应的内容。

  1. Content-(response.content)-类似于 beautifulsoup的库接受二进制输入
  2. JSON (response.json())-大多数 API 调用只以这种格式给出响应
  3. 文本(response.text)-用于任何目的,包括基于正则表达式的搜索,或转储数据到一个文件等。

根据网页的类型,你可以使用相应的属性。