scrapy数据保存为excel

本文介绍了如何使用Scrapy爬虫抓取的数据并保存到Excel文件中,通过openpyxl模块实现。首先安装openpyxl库,然后在pipelines.py文件中创建ExcelPipeline,初始化工作簿和工作表,设置表头,并在处理每个item时将数据写入相应单元格,最后保存并关闭文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、概述

scrapy爬取的数据,需要保存到excel中,根据中文标题,将对应的数据写入。

二、实现方法

安装模块

pip3 install openpyxl

修改pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from openpyxl import Workbook


class ExcelPipeline(object):
    def __init__(self):
        self.wb = Workbook()
        self.ws = self.wb.active
        self.ws.append(['姓名', '年龄', '地址')
        self.file_name = "test.xlsx"

    def process_item(self, item, spider):
        line = [item['name'], item['age'], item['address']]
        self.ws.append(line)
        self.wb.save(self.file_name)
        return item

    def close_spider(self, spider):
        # 关闭
        self.wb.close()

本文参考链接:

https://blog.youkuaiyun.com/qq_42336560/article/details/80951401

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值