[英]Python Requests response decode
I send a request using python requests and then print the response, what confuse me is that the Chinese characters in response is something like \数\据\返\回\成\功我使用python请求发送请求,然后打印响应,让我困惑的是响应中的汉字类似于\数\据\返\回\成\功
Here is the code:这是代码:
# -*- coding:utf-8 -*-
import requests
url = "http://www.biyou888.com/api/getdataapi.php?ac=3005&sess_token=&urlid=-1"
res = requests.get(url)
if res.status_code == 200:
print res.text
Below is the response下面是回复
What should i do to tranfer the response?我应该怎么做才能传输响应? I have try to use encode and decode but it dose work.
我尝试使用编码和解码,但它起作用了。
Use requests.Response.json and you will get the chinese caracters.使用 requests.Response.json,您将获得中文字符。
import requests
import json
url = "http://www.biyou888.com/api/getdataapi.phpac=3005&sess_token=&urlid=-1"
res = requests.get(url)
if res.status_code == 200:
res_payload_dict = res.json()
print(res_payload_dict)
For illustrate, let's ping API of Github.为了说明,让我们ping Github 的API。
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com')
# print response
print(response)
# print encoding of response
print(response.encoding)
output:输出:
<Response [200]>
utf-8
So, in your example, try res.json()
instead of res.text
?所以,在你的例子中,尝试
res.json()
而不是res.text
?
As in:如:
# encoding of your response
print(res.encoding)
res.encoding='utf-8-sig'
print(res.json())
sig
in utf-8-sig
is the abbreviation of signature
(ie signature utf-8 file). sig
在utf-8-sig
是的缩写signature
(即签名UTF-8文件)。
Using utf-8-sig
to read a file will treat BOM as file info instead of a string.使用
utf-8-sig
读取文件会将 BOM 视为文件信息而不是字符串。
import requests
import json
url = "http://www.biyou888.com/api/getdataapi.php?ac=3005&sess_token=&urlid=-1"
res = requests.get(url)
res_dict = {}
if res.status_code == 200:
print type(res.text)
print res.text
res_dict = json.loads(res.text) # get a dict from parameter string
print "Dict:"
print type(res_dict)
print res_dict
print res_dict['info']
Use json
module to parse that input.使用
json
模块来解析该输入。 And the prefix u
just means it is a unicode string.前缀
u
仅表示它是一个 unicode 字符串。 When you use them, the u
prefix won't affect, just like what I show at the last several lines.当你使用它们时,
u
前缀不会影响,就像我在最后几行显示的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.