zoukankan      html  css  js  c++  java
  • json解析模块

    json.loads(json)

    作用:把json格式的字符串转为Python数据类型

    示例:html_json = json.loads(res.text)

    json.dumps(python)

    作用:把 python 类型 转为 json 类型

    示例:

    import json
    
    # json.dumps()之前
    item = {'name':'QQ','app_id':1}
    print('before dumps',type(item))
    # before dumps <class 'dict'> 
    # json.dumps之后
    item = json.dumps(item)
    print('after dumps',type(item))
    # after dumps <class 'str'> 

    json.load(f)

    作用:将json文件读取,并转为python类型

    json.dump(python,f,ensure_ascii=False)

    作用:把python数据类型 转为 json格式的字符串

      # 一般让你把抓取的数据保存为json文件时使用

    参数说明:

    第1个参数: python类型的数据(字典,列表等)
    第2个参数: 文件对象
    第3个参数: ensure_ascii=False # 序列化时编码

    示例:

    import json
    
    # 示例1
    item = {'name': '金毛狮王', 'card': '屠龙刀'}
    with open('yt.json', 'a') as f:
      json.dump(item, f, ensure_ascii=False)
    
    
    # json.load() 把文件中的json串读取并转为python数据类型
    with open('yt.json', 'r') as f:
      res = json.load(f)
    
    print(type(res))
    #<class 'dict'>
    
    # 示例2
    item_list = [
      {'name': '紫衫龙王', 'card': '123'},
      {'name': '青翼蝠王', 'card': '456'}
    ]
    
    with open('yy.json', 'a') as f:
      json.dump(item_list, f, ensure_ascii=False)

    示例:

    import json
    
    item_list = []
    for i in range(3):
      item = {'name': 'QQ', 'id': i}
      item_list.append(item)
    
    with open('xiaomi.json', 'a') as f:
      json.dump(item_list, f, ensure_ascii=False)
      
    #[{"name": "QQ", "id": 0}, {"name": "QQ", "id": 1}, {"name": "QQ", "id": 2}]

    练习:将腾讯招聘数据存入到json文件

    # 1. __init__()
        self.f = open('tencent.json','a')
        self.item_list = []
    # 2. parse_page()
        self.item_list.append(item)
    # 3. main()
        json.dump(self.item_list,self.f,ensure_ascii=False)
        self.f.close()

    json模块总结

    # 爬虫最常用
    1、数据抓取 - json.loads(html)
       将响应内容由: json 转为 python
    2、数据保存 - json.dump(item_list,f,ensure_ascii=False)
       将抓取的数据保存到本地 json文件
    
    # 抓取数据一般处理方式
    1、txt文件
    2、csv文件
    3、json文件
    4、MySQL数据库
    5、MongoDB数据库
    6、Redis数据库

     

     

  • 相关阅读:
    Javascript FP-ramdajs
    微信小程序开发
    SPA for HTML5
    One Liners to Impress Your Friends
    Sass (Syntactically Awesome StyleSheets)
    iOS App Icon Template 5.0
    React Native Life Cycle and Communication
    Meteor framework
    RESTful Mongodb
    Server-sent Events
  • 原文地址:https://www.cnblogs.com/maplethefox/p/11360452.html
Copyright © 2011-2022 走看看