当前位置: 首页> 健康> 知识 > 爬虫笔记12——网页爬取数据写入json文件

爬虫笔记12——网页爬取数据写入json文件

时间:2025/7/9 16:31:55来源:https://blog.csdn.net/Yima_Dangxian/article/details/139785881 浏览次数:0次

json数据格式介绍

JSON全称为JavaScript Object Notation, 也就是JavaScript对象标记,它通过对象和数组的组合来表示数据,构造简洁但是结构化程度非常高,是一种轻量级的数据交换格式。该笔记中,我们就来了解如何利用Python保存数据到JSON文件。

python中的json库

直接导入该模块:

import json
方法作用
json.dumps()把python对象转换成json对象,生成的是字符串。
json.dump()用于将dict类型的数据转成str,并写入到json文件中

爬虫案例 - 4399网站游戏信息采集


import json
import requests
from lxml import etreedef spider_4399(url):response = requests.get(url).content.decode('gbk')# print(response)tree = etree.HTML(response)# print(tree)gameLists = tree.xpath("//ul[@class='tm_list']/li/a")gameDicts = dict()result = list()# print(gameLists)for temp in gameLists:gameDicts['game'] = temp.xpath('./text()')[0]gameDicts['url'] = temp.xpath('./@href')[0]result.append(gameDicts)with open('./game.json', 'w', encoding='utf-8') as f:f.write(json.dumps(result, indent=2, ensure_ascii=False))print('程序结束!')url = 'https://www.4399.com/'
spider_4399(url)
关键字:爬虫笔记12——网页爬取数据写入json文件

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: