在爬虫过程中,常需要拿到接口来解析返回的json数据,方法有很多,传统的做法便是一层一层的取数据,这样过于麻烦,还耗时,于是找到了JsonPath这样的神器
一、JsonPath的优势
1、操作方式简单
2、有通用的表达式获取指定的值
3、减少代码量和内存消耗
4、依赖于强大的XPath库
二、使用方法
1、JsonPath的操作符
| 操作 | 说明 |
|---|---|
| $ | 查询根元素。这将启动所有路径表达式 |
| @ | 当前节点由过滤谓词处理 |
| * | 通配符,必要时可用任何地方的名称或数字 |
| .. | 深层扫描,必要时在任何地方可以使用名称 |
| . |
点,表示子节点 |
| [‘ |
括号表示子项 |
| [ |
数组索引或索引 |
| [start:end] | 数组切片操作 |
| [?( |
过滤表达式,表达式必须求值为一个布尔值引 |
2、使用JsonPath
2.1 json数据:
{
"code": 200,
"current": 1,
"msg": "操作成功",
"pages": 1,
"product_all": [{
"created_at": "2021-10-20 15:52:26",
"id": 4,
"product_description": "",
"product_name": "云大学",
"product_sign": "YUN",
"product_type": 0,
"producter": "Init"
}, {
"created_at": "2021-07-16 16:23:44",
"id": 3,
"product_description": "--",
"product_name": "APP",
"product_sign": "APP",
"product_type": 0,
"producter": "Init"
}, {
"created_at": "2021-07-16 15:53:01",
"id": 2,
"product_description": "--",
"product_name": "WEB",
"product_sign": "WEB",
"product_type": 0,
"producter": "Init"
}],
"total": 3
}
2.2 python语法
import jsonpath
class AnalysisJson:
def __init__(self, result, element):
self.result = result
self.element = element
def JsonResult(self):
"""
:param result: 返回值
:param element: 元素名称
:return: city: 筛选后的结果
"""
result = jsonpath.jsonpath(self.result, self.element)
return result
2.3 测试结果
| 操作 | 说明 |
|---|---|
| $.code | 取到code的值 |
| $.product_all[..product_name] | 取到所有product_name值 |
| $.product_all[0,1][..product_name] | 取到前两个list中product_name的值 |
