一.安装
1.同xpath篇一样找到安装路径,具体图片如下:
2.查看是否安装成功:
二.使用
1.jsonpath对应的 json 字符串:
{
"store": {
"book": [{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
}, {
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}, {
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
}, {
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
2.xpath和jsonpath的对比:
3.jsonpath查找节点结果示例:
import json
import jsonpath
obj = json.load(open('解析_jsonpath.json', 'r', encoding='utf-8'))
# 书店所有书的作者即所有book的author节点
author_list = jsonpath.jsonpath(obj, '$.store.book[*].author')
print(author_list)
三.案例
1.获取 json 数据并保存至本地
import urllib.request
url = 'https://dianying.taobao.com/cityAction.json?activityId&_ksTS=1679306734047_108&jsoncallback=jsonp109&action=cityAction&n_s=new&event_submit_doGetAllRegion=true'
headers = {
'accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
# 'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'bx-v': '2.2.3',
'cookie': "cna=Q4AUHKqROiYCAXWFM3jmP2wl; t=857710425004b8b3af9cbd4ea5892468; cookie2=187fe46494bde6a854d98197651f42a4; v=0; _tb_token_=eddee0183e67e; xlly_s=1; l=fBrhnmSnTmYeA136BO5Bnurza779uIRb8tFzaNbMiIEGa6FhTFagTNCsB4qD7dtjgTfx2etz1WWCvdEJyAaLRFsWHpfuKtyuJrv6-bpU-L5..; tfstk=cRrABOTiO_fDcC5i4mQk7SwvecEAZ59xsKG9XkWabBGf9ytOiUr3vKxGlAlEMTC..; isg=BJmZsARkGRDIJMIRubqYLSAtqIVzJo3YQx3L57tOgUA_wrhUA3IGqPicxIa0uCUQ",
'referer': 'https://dianying.taobao.com/',
'sec-ch-ua': '"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'user-agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
'x-requested-with': 'XMLHttpRequest'
}
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
# split切割
content = content.split('(')[1].split(')')[0]
print(content)
with open('解析_jsonpath淘票票.json', 'w', encoding='utf-8')as fp:
fp.write(content)
# shift+alt+l对json格式文件进行格式化
2.根据本地 json 文件获取相应信息
import json
import jsonpath
obj = json.load(open('解析_jsonpath淘票票.json', 'r', encoding='utf-8'))
city_list = jsonpath.jsonpath(obj, '$..regionName')
print(city_list)
结果:
红框内的为最终结果,因此需要对字符串进行切割,获取最终结果如下:
黄框为最终结果,绿框为jsonpath解析完字段reginName的结果。