Python如何正确将“爬虫数据”以json格式进行保存

56 阅读1分钟

在Python中将爬虫数据保存为JSON格式,主要涉及数据提取、格式转换和文件写入三个关键环节。

1.数据处理与转换

JSON采用键值对结构,键必须是字符串且使用双引号包围,值可以是字符串、数字、布尔值、数组或对象。Python中通过json.dump()和json.dumps()函数实现对象序列化,其中dump()直接将对象写入文件流,dumps()则生成JSON格式字符串。

2.核心参数配置

ensure_ascii=False:确保中文字符正常显示而非Unicode转义

indent=4:设置输出缩进,提升文件可读性

encoding='utf-8':指定文件编码格式

3.完整实现流程

 
import requests
from bs4 import BeautifulSoup
import json
 
def crawl_and_save_json():
    # 配置请求参数
    url = "https://example.com/news"
    
    try:
        # 发送网络请求
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        
        # 解析HTML内容
        soup = BeautifulSoup(response.text, 'html.parser')
        news_items = soup.find_all('div', class_='news-item')
        
        # 构建数据列表
        news_data = []
        for item in news_items:
            title = item.find('h2').text.strip()
            link = item.find('a')['href']
            
            news_item = {
                'title': title,
                'link': link
            }
            news_data.append(news_item)
        
        # 保存为JSON文件
        with open('news_data.json', 'w', encoding='utf-8') as f:
            json.dump(news_data, f, 
                      ensure_ascii=False, 
                      indent=4)
        
        print("数据已成功保存至news_data.json")
        
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
 
if __name__ == "__main__":
    crawl_and_save_json()

该代码演示了完整的爬虫数据JSON保存流程:通过requests获取网页数据,使用BeautifulSoup解析提取目标信息,构建Python字典列表,最后通过json.dump()写入文件。关键配置包括设置UTF-8编码避免乱码,禁用ASCII转换确保中文正常显示,以及使用缩进格式化输出。

对于直接从API获取的JSON数据,可直接使用response.json()方法解析,避免复杂的文本处理流程。

image.png