Python爬虫——解析_jsonpath

jsonpath的安装

pip install jsonpath

jsonpath的使用:

obj = json.load(open('json文件', 'r', encoding='utf-8'))
ret = jsonpath.jsonpath(obj, 'jsonpath语法')

json文件:

{ "store": {
    "book": [
      { "category": "末世",
        "author": "晨星LL",
        "title": "这游戏也太真实了",
        "price": 8.95
      },
      { "category": "玄幻",
        "author": "辰东",
        "title": "遮天",
        "price": 12.99
      },
      { "category": "御兽",
        "author": "清泉流响",
        "title": "不科学御兽",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "科幻",
        "author": "我吃西红柿",
        "title": "吞噬星空",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "author": "车厂",
      "color": "blue",
      "price": 19.95
    }
  }
}
  • 书店所有书的作者
# *代表全部   可以根据下标来获取第几本书
book_list = jsonpath.jsonpath(obj, '$.store.book[*].author')
print(book_list)
  • 所有的作者
book_list = jsonpath.jsonpath(obj, '$..author')
print(book_list)
  • store下面所有的元素
book_list = jsonpath.jsonpath(obj, '$.store[*]')
print(book_list)
  • store里面所有东西的price
book_list = jsonpath.jsonpath(obj, '$.store..price')
print(book_list)
  • 第三本书
book_list = jsonpath.jsonpath(obj, '$..book[2]')
print(book_list)
  • 最后一本书
book_list = jsonpath.jsonpath(obj, '$..book[(@.length-1)]')
print(book_list)
  • 前两本书
# 两种写法
book_list = jsonpath.jsonpath(obj, '$..book[0,1]')
book_list = jsonpath.jsonpath(obj, '$..book[:2]')
print(book_list)
  • 条件过滤需要在()的前面添加一个?
  • 过滤出所有包含isbn的书
book_list = jsonpath.jsonpath(obj, '$..book[?(@.isbn)]')
print(book_list)
  • 哪本书超过了10块钱
book_list = jsonpath.jsonpath(obj, '$..book[?(@.price>10)]')
print(book_list)

参考:https://blog.csdn.net/Obstinate_L/article/details/125294971

你可能感兴趣的:(Python爬虫,python,爬虫)