目录
前置知识
一、 json.loads():JSON 转 Python 数据
二、json.dump():python数据 转 json 并写入文件
三、json.loads() :json 转 python数据
四、json.load() :json 转 python数据(在文件操作中更方便)
五、实战案例
完整代码演示
前置知识
1,不涉及文件操作 json 字符串 => 转换成 => python 数据类型 :json.loads() python 数据类型 => 转换成 => json 字符串 :json.dumps() 2,涉及文件操作 包含 json 的类文件对象 => 转换成 => python 数据类型 :json.load() python 数据类型 => 转换成 => 包含 json 的类文件对象 :json.dump() # 总结:不加 s 涉及到文件操作
json用于数据交换
JS(前端) -> json -> python(后端)
python(后端) -> json -> JS(前端)
一、 json.loads():JSON 转 Python 数据
import json
# 1,python数据类型 转 json字符串
# python 字典数据
dic = {'a':1,'b':2}
print(type(dic)) #打印类型:字典类型
# 2,python数据 转成 json数据
json1 = json.dumps(dic)
# 3,打印结果
print(type(json1)) #结果是str,就是json字符串
# 4,增加键值
dic[('2',1)] = '元组' #错误,不能这样添加
dic["c"]='元组' # 正确
# 5,json数据key不能是元组,skipkeys=True可以过滤异常数据,ensure_ascii=False可以解决编码问题
json2 = json.dumps(dic,skipkeys=True,ensure_ascii=False)
print(json2)
print(type(json2))
二、json.dump():python数据 转 json 并写入文件
import json
# 1,python字典数据
dic = {'a':1,'b':2}
with open('text.json','w',encoding='utf-8') as f:
# 参数1:要转成json格式并保存的数据
# 参数2:文件指针
json.dump(dic,f,skipkeys=True,ensure_ascii=False)
三、json.loads() :json 转 python数据
import json
# text.json中是刚才存储的 json 数据
with open('text.json','r',encoding='utf-8') as f:
data = f.read()
print(data)
print(type(data)) #json字符串
# 转换
dic = json.loads(data) # python字典
print(type(dic))
四、json.load() :json 转 python数据(在文件操作中更方便)
import json
# text.json中是刚才存储的 json 数据
with open('text.json','r',encoding='utf-8') as f:
# 转换
dic = json.load(f) #python字典
print(f"字典数据:{dic}\n类型:{type(dic)}")
五、实战案例
需求:爬取腾讯招聘信息的《标题》《城市》《日期》
链接:搜索 | 腾讯招聘
分析步骤:
1,找到目标url
目标URL:https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1740842427771&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=1&keyword=&pageIndex=1&pageSize=10&language=zh-cn&area=cn
2,分析响应数据
可以进一步验证:
将数据全选复制进入 在线代码格式化 验证是否为 json 格式
3,分析一下数据内容
我们需要的数据层级关系,转换成字典后:
Data > Posts > 列表n > RecruitPostName(标题) LocationName(城市) LastUpdateTime(日期)特别注意:Posts是一个列表
完整代码演示
import json
import requests
# 1,目标url
url = 'https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1740842427771&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=1&keyword=&pageIndex=1&pageSize=10&language=zh-cn&area=cn'
# 2,身份伪装
header={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36"
}
# 3,发起请求获取响应
response = requests.get(url=url,headers=header)
# 4,打印响应内容
# print(response.text)
print(type(response.text)) #json字符串类型
# 5,将json字符串转换成python数据
result = json.loads(response.text)
print(type(result)) # 字典类型
# 6,提取需要的信息:标题+城市+日期
title = result['Data']['Posts']
for tit in title:
# print(tit)
print(f"{tit['RecruitPostName']} ,{tit['LocationName']} ,{tit['LastUpdateTime']}")
# 字符串替换:result = str.replace(r'\n','')
拓展
实现多页爬取分析步骤
1.分别获取到第一页、第二页、第三页的 url 对比
# 第一页
https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1740904582702&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=1&keyword=&pageIndex=1&pageSize=10&language=zh-cn&area=cn
# 第二页
https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1740904630357&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=1&keyword=&pageIndex=2&pageSize=10&language=zh-cn&area=cn
# 第三页
https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1740904538329&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=1&keyword=&pageIndex=3&pageSize=10&language=zh-cn&area=cn
# 特别提醒:测试可以直接将上面的url放入导航栏查看响应数据,还有可以删掉一些参数查看对响应数据有没有影响
对比之后发现只有两个地方不同
1, pageIndex 页数
2, timestamp 时间戳测试后发现,时间戳固定对爬取数据没有任何影响,因此多页爬取只需要变化 pageIndex 的值即可
# 伪代码:
for i in range(1,11):
url = f"https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1740904630357&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=1&keyword=&pageIndex={i}&pageSize=10&language=zh-cn&area=cn"
# 这样就可以得到十页的url了,剩下的爬取工作是一样的
print(url)