Python爬虫JSON及JSONPath运行原理详解

2020-10-05 0 955

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。适用于进行数据交互的场景,比如网站前台与后台之间的数据交互。

JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:Javascript, Python, PHP 和 Java。

JsonPath 对于 JSON 来说,相当于 XPATH 对于 XML。

JsonPath与XPath语法对比:

Json结构清晰,可读性高,复杂度低,非常容易匹配,下表中对应了XPath的用法。

Python爬虫JSON及JSONPath运行原理详解

相关推荐:《Python相关教程》

利用JSONPath爬取拉勾网上所有的城市

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2
# json解析库,对应到lxml
import json
# json的解析语法,对应到xpath
import jsonpath
url = \"http://www.lagou.com/lbs/getAllCitySearchLabels.json\"
headers = {\'User-Agent\':\'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36\'}
request = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(request)
# 取出json文件里的内容,返回的格式是字符串
html = response.read()
# 把json形式的字符串转换成python形式的Unicode字符串
unicodestr = json.loads(html)
# Python形式的列表
city_list = jsonpath.jsonpath(unicodestr, \"$..name\")
#for item in city_list:
#  print item
# dumps()默认中文为ascii编码格式,ensure_ascii默认为Ture
# 禁用ascii编码格式,返回的Unicode字符串,方便使用
array = json.dumps(city_list, ensure_ascii=False)
#json.dumps(city_list)
#array = json.dumps(city_list)
with open(\"lagoucity.json\", \"w\") as f:
  f.write(array.encode(\"utf-8\"))

结果:

Python爬虫JSON及JSONPath运行原理详解

糗事百科爬取

利用XPATH的模糊查询

获取每个帖子里的内容

保存到 json 文件内

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2
import json
from lxml import etree
url = \"http://www.qiushibaike.com/8hr/page/2/\"
headers = {\'User-Agent\':\'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36\'}
request = urllib2.Request(url, headers = headers)
html = urllib2.urlopen(request).read()
# 响应返回的是字符串,解析为HTML DOM模式 text = etree.HTML(html)
text = etree.HTML(html)
# 返回所有段子的结点位置,contains()模糊查询方法,第一个参数是要匹配的标签,第二个参数是标签名部分内容
node_list = text.xpath(\'//div[contains(@id, \"qiushi_tag\")]\')
items ={}
for node in node_list:
  # xpath返回的列表,这个列表就这一个参数,用索引方式取出来,用户名
  username = node.xpath(\'./div/a/@title\')[0]
  # 取出标签下的内容,段子内容
  content = node.xpath(\'.//div[@class=\"content\"]/span\')[0].text
  # 取出标签里包含的内容,点赞
  zan = node.xpath(\'.//i\')[0].text
  # 评论
  comments = node.xpath(\'.//i\')[1].text
  items = {
    \"username\" : username,
    \"content\" : content,
    \"zan\" : zan,
    \"comments\" : comments
  }
  with open(\"qiushi.json\", \"a\") as f:
    f.write(json.dumps(items, ensure_ascii=False).encode(\"utf-8\") + \"
\")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

遇见资源网 Python Python爬虫JSON及JSONPath运行原理详解 http://www.ox520.com/25909.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务