zoukankan      html  css  js  c++  java
  • 爬虫——json模块与jsonpath模块

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

    JSON和XML相比较可谓不相上下。

    Python 3.X中自带了JSON模块,直接import json就可以使用了。

    官方文档:http://docs.python.org/library/json.html

    Json在线解析网站:http://www.json.cn/#

    JSON

    json简单来说就是JavaScript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。

    1. 对象:对象在js中表示为{ }括起来的内容,数据结构为{key1: value1, key2:value2, ...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是数字、字符串、数组、对象。
    2. 数组:数组在js中是[ ]括起来的内容,数据结构为['Python', ‘JavaScript', 'C++', ...],取值方式和所有语言一样,使用索引获取,字段值的类型可以是数字、字符串、数组、对象。

    json模块

    json模块提供了四个功能:dumps、dump、loads、load,用于字符串和Python数据类型间进行转换。

    1.json.dumps()

    实现Python类型转化为Json字符串,返回一个str对象,从Python到Json的类型转换对照如下:

    Python Json
    dict object
    list, tuple array
    str, utf-8 string
    int, float number
    True true
    False false
    None null  
    #!/usr/bin/python3
    # -*- coding:utf-8 -*-
    __author__ = 'mayi'
    
    import json
    
    listStr = [1, 2, 3, 4]
    tupleStr = (1, 2, 3, 4)
    dictStr = {"city": "北京", "name": "蚂蚁"}
    
    print(json.dumps(listStr))
    # [1, 2, 3, 4]
    
    print(type(json.dumps(listStr)))
    # <class 'str'>
    
    print(json.dumps(tupleStr))
    # [1, 2, 3, 4]
    
    print(type(json.dumps(tupleStr)))
    # <class 'str'>
    
    # 注意:json.dumps() 序列化时默认使用的ascii编码
    # 添加参数 ensure_ascii=False 禁用ascii编码,按utf-8编码
    print(json.dumps(dictStr, ensure_ascii = False))
    # {"city": "北京", "name": "蚂蚁"}
    
    print(type(json.dumps(dictStr, ensure_ascii = False)))
    # <class 'str'>
    

    2.json.dump()

     将Python内置类型序列化为Json对象后写入文件

    #!/usr/bin/python3
    # -*- coding:utf-8 -*-
    __author__ = 'mayi'
    
    import json
    
    listStr = [{"city": "北京"}, {"name": "蚂蚁"}]
    json.dump(listStr, open("listStr.json", "w", encoding = "utf-8"), ensure_ascii = False)
    
    dictStr = {"city": "北京", "name": "蚂蚁"}
    json.dump(dictStr, open("dictStr.json", "w", encoding = "utf-8"), ensure_ascii = False)
    

     3.json.loads()

    把Json格式字符串解码转换成Python对象,从Json到Python的类型转换对照如下:

    Json Python
    object dict
    array list
    string utf-8
    number(int) int
    number(real) float
    true True
    false False
    null None
    #!/usr/bin/python3
    # -*- coding:utf-8 -*-
    __author__ = 'mayi'
    
    import json
    
    strList = '[1, 2, 3, 4]'
    
    strDict = '{"city": "北京", "name": "蚂蚁"}'
    
    print(json.loads(strList))
    # [1, 2, 3, 4]
    
    # json数据自动按utf-8存储
    print(json.loads(strDict))
    # {'city': '北京', 'name': '蚂蚁'}
    

    4.json.load()

    读取文件中Json形式的字符串,转换成Python类型

    #!/usr/bin/python3
    # -*- coding:utf-8 -*-
    __author__ = 'mayi'
    
    import json
    
    strList = json.load(open("listStr.json", "r", encoding = "utf-8"))
    print(strList)
    # [{'city': '北京'}, {'name': '蚂蚁'}]
    
    strDict = json.load(open("dictStr.json", "r", encoding = "utf-8"))
    print(strDict)
    # {'city': '北京', 'name': '蚂蚁'}
    

    JsonPath

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

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

    JsonPath与XPath语法对比:

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

     
    Xpath JSONPath 描述
    / $ 根节点
    . @ 现行节点
    / . or [] 取子节点
    .. n/a 取父节点,Jsonpath未支持
    // .. 不管位置,选择所有符合条件的节点
    * * 匹配所有元素节点
    @ n/a 根据属性访问,JsonPath不支持
    [] [] 迭代器(可以在里边做简单的迭代操作,如数组下标,根据内容选值等)
    | [,] 支持迭代器中做多选
    [] ?() 支持过滤操作
    n/a () 支持表达式计算
    () n/a 分组,JsonPath不支持

    示例:

    以拉勾网城市JSON文件:http://www.lagou.com/lbs/getAllCitySearchLabels.json 为例,获取所有的城市名称。

    #!/usr/bin/python3
    # -*- coding:utf-8 -*-
    __author__ = 'mayi'
    
    import urllib.request
    import json
    import jsonpath
    
    # 拉勾网城市JSON文件
    url = 'http://www.lagou.com/lbs/getAllCitySearchLabels.json'
    # User-Agent头
    header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'}
    
    # url 连同 headers,一起构造Request请求,这个请求将附带 chrome 浏览器的User-Agent
    request = urllib.request.Request(url, headers = header)
    
    # 向服务器发送这个请求
    response = urllib.request.urlopen(request)
    
    # 获取页面内容:bytes
    html = response.read()
    
    # 转码:bytes转str
    html = html.decode("utf-8")
    
    # 把json格式字符串转换成python对象
    obj = json.loads(html)
    
    # 从根节点开始,匹配name节点
    city_list = jsonpath.jsonpath(obj, '$..name')
    
    # 打印获取的name节点
    print(city_list)
    # 打印其类型
    print(type(city_list))
    
    # 写入本地磁盘文件
    with open("city.json", "w", encoding = "utf-8") as f:
        content = json.dumps(city_list, ensure_ascii = False)
        f.write(content)
    
  • 相关阅读:
    webpack 知识点
    freemarker知识点
    js知识点
    oracle 安装介绍
    CentOS 7.4x64 系统安装完成后配置
    centos 7 互信【ssh】
    spark与mapreduce的最大区别和spark原理
    最简单的搭建SpringBoot框架步骤
    simplify(s)
    ezplot函数
  • 原文地址:https://www.cnblogs.com/mayi0312/p/7225532.html
Copyright © 2011-2022 走看看