爬虫学习(十六)——jsonpath

jsonpath介绍

jsonpath是一种信息抽取类库,是从json文档中抽取指定信息的工具,提供多种语言实现的版本

jsonpath对json来说,就相当于xpath对于xml

 

jsonpath和xpath的语法对比

jsonpath用一个抽象的名字$来表示最外层对象

 

网络上请求json数据的方式

import requests
# 请求json数据,使用requests模块
response =requests.get(url=url,headers=headers)
# 对json进行解码,解码utf8格式
response.encoding=("utf8")
# 获取json的content属性
content = response.content

案例一

# jsonpath的索引从0开始,区别于xpath从1开始

shu01 = jsonpath.jsonpath( shudata, "$.store.book" )
print( shu01 )
# 输出结果:[[{'category': 'reference', 'author': '李白', 'title': 'Sayings of the Century', 'price': 8.95}, {'category': 'fiction', 'author': '杜甫', 'title': 'Sword of Honour', 'price': 12.99}, {'category': 'fiction', 'author': '白居易', 'title': 'Moby Dick', 'isbn': '0-553-21311-3', 'price': 8.99}, {'category': 'fiction', 'author': '苏轼', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]]
shu0 =jsonpath.jsonpath(shudata,"$.store.book[1]")
print(shu0)
# 输出结果:显示第二个对象
# [{'category': 'fiction', 'author': '杜甫', 'title': 'Sword of Honour', 'price': 12.99}]

案例二
# 加载json文件,读成数据流

fp = open("lagou_json.json","r",encoding="utf8")
# 将数据流加载成python中显示的json格式数据
jsondata = json.load(fp)
# 解析当前json数据
# 如:或取中国A开头的市级行政区名
city = jsonpath.jsonpath(jsondata,'$..[A].[name]')
print(city)
# 输出结果:['安庆', '安顺', '安康', '澳门特别行政区', '鞍山', '安阳', '阿坝藏族羌族自治州']


案例三

# 查找数的价格大于10元的书对象
shu = jsonpath.jsonpath(shudata,"$..book[?(@.price>10)]")
print(shu)
# 输出结果:
# 输出结果:[{'category': 'fiction', 'author': '杜甫', 'title': 'Sword of Honour', 'price': 12.99}, {'category': 'fiction', 'author': '苏轼', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]

案例四
# 查找json对象中含有‘isbn’属性的json对象
shu1 =jsonpath.jsonpath(shudata,"$..book[?(@.isbn)]")
print(shu1)
# 输出结果:[{'category': 'fiction', 'author': '白居易', 'title': 'Moby Dick', 'isbn': '0-553-21311-3', 'price': 8.99}, {'category': 'fiction', 'author': '苏轼', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
 

 

posted @ 2019-02-19 09:02  石桥浪子  阅读(271)  评论(0编辑  收藏  举报