Python请求二进制内容
我试图从Google趋势URL获取JSON,但我无法将其转换为JSON,因为内容为b“”。如何将此结果作为JSON获取 我的简单代码:Python请求二进制内容,python,json,binary,python-requests,Python,Json,Binary,Python Requests,我试图从Google趋势URL获取JSON,但我无法将其转换为JSON,因为内容为b“”。如何将此结果作为JSON获取 我的简单代码: import requests r = requests.get('https://trends.google.ru/trends/api/stories/latest?hl=ru&tz=-180&cat=all&fi=15&fs=15&geo=RU&ri=300&rs=15&sort=0') pr
import requests
r = requests.get('https://trends.google.ru/trends/api/stories/latest?hl=ru&tz=-180&cat=all&fi=15&fs=15&geo=RU&ri=300&rs=15&sort=0')
print(r.content)
r.content
以以下内容开头:
(b)b)b)b)7)b)6)b)7)b)7)b)7)b)7)b)7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7)6)6)6)7 7 7 7 7 7 7 7 7 7 7 7)6)6)7 7)7 7)7 7 7)7 7 7 7)6)6)6)6)7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 qs1aawaabvmm_RU”,“RU_lnk_TJ8D1AAwAABP-M_RU”,“RU_lnk_I97F0wAwAADmvM_RU”、“RU_lnk_tCrq0wAwAABeSM_RU”、“RU_lnk_w8ea1awabpm_RU”、“RU_lnk_iyx90wawaadc5 m_RU”、“RU_lnk_bz4m1awabjwm_RU”、“RU_lnk_EJ-
使用r.json()
方法对此进行解码失败:
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
您正在联系Google服务,Google正在为JSON添加一些额外数据,以: 注意开头的
)]}
和换行符
您需要先删除此额外数据并手动解码;有效负载中没有其他换行符,因此我们可以在换行符上拆分:
import json
json_body = r.text.splitlines()[-1]
json_data = json.loads(json_body)
我在这里使用Response.text
来获取解码的字符串数据(服务器在标题中设置了正确的内容类型编码)
这将为您提供一个解码字典:
>>> json_body = r.text.splitlines()[-1]
>>> json_data = json.loads(json_body)
>>> type(json_data)
<class 'dict'>
>>> sorted(json_data)
['date', 'featuredStoryIds', 'hideAllImages', 'storySummaries', 'trendingStoryIds']
json_body=r.text.splitlines()[-1]
>>>json_data=json.loads(json_body)
>>>类型(json_数据)
>>>已排序(json_数据)
['date','FeaturedStoryId','hideAllImages','storySummaries','trendingStoryIds']
也许可以试试这个,它可能会有帮助:
import requests
r = requests.get('https://trends.google.ru/trends/api/stories/latest?hl=ru&tz=-180&cat=all&fi=15&fs=15&geo=RU&ri=300&rs=15&sort=0')
page=r.status_code
print page
r.content
确实是原始二进制数据。你看过那张照片了吗?调用时会发生什么?是的,simplejson.scanner.JSONDecodeError:期望值:第1行第1列(char 0)TypeError:JSON对象必须是str,而不是“bytes”@KonstantinRusanov:ah,较旧的Python 3版本,3.6接受字节。将更新。完美!谢谢
import requests
r = requests.get('https://trends.google.ru/trends/api/stories/latest?hl=ru&tz=-180&cat=all&fi=15&fs=15&geo=RU&ri=300&rs=15&sort=0')
page=r.status_code
print page