Python_json类方法
Python_json类方法
import requests
import json
headers = {
"User-Agent": "Mozilla/5.0 (Linux Android 6.0Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Mobile Safari/537.36"
}
url = "https://m.toutiao.com/list/?tag=__all__&max_time=0&min_behot_time=0&ac=wap&count=20&format=json_raw&_signature=zDO00gAAr-RscdJ0dNc1tswztM&i=&as=A196A32E19BD4E3&cp=63E95DB45E63CE1&aid=1698"
response = requests.get(url, headers=headers)
j = response.content.decode()
# json.loads把json字符串转成称python类型
ret1 = json.loads(j)
print(type(ret1)) # <class 'dict'>
# json.dumps 能把python字典转换称json字符串
# ret2 = json.dumps(ret1)
# print(type(ret2)) # <class 'str'>
with open("jinritoutiao.json", "w", encoding="utf-8") as f:
# ensure_ascii:这是因为json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False
# indent:缩进字符
f.write(json.dumps(ret1, ensure_ascii=False, indent=4))
# 提取json字符串中的新闻摘要,输出到txt中
with open("result.txt", "w", encoding="utf-8") as f:
for i in range(15):
f.write("第{}条: {}\n".format(i+1, ret1["data"][i]["abstract"]))
# json.load and json.dump
# 具有read或者write方法的对象就是类文件对象
# 读取json的类文件对象
with open("./jinritoutiao.json", "r", encoding="utf-8") as f:
print(json.load(f))
# 写入json的类文件对象
with open("./jinritoutiao1.json", "w", encoding="utf-8") as f:
json.dump(ret1, f, ensure_ascii=False, indent=4)
作者:Hovey
出处:https://www.cnblogs.com/thankcat/p/17117812.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
分类:
Python Spider
Buy me a cup of coffee ☕.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?