python - 将 CSV 文件记录与 Python Scrapy 输出数据进行比较

标签 python csv web-scraping scrapy web-crawler

我是 Python 和网络抓取新手。请原谅我的无知。在这个程序中,我抓取了一些网址并将产品名称和价格保存到 csv 文件中。当我再次运行脚本时,我想读取现有的 csv 记录(产品名称和价格),如果任何产品的价格发生变化,我想打印一条消息。我正在努力实现该程序的第二部分,即将值与保存的 csv 记录进行比较。请帮忙。任何帮助将不胜感激。

import scrapy
from time import sleep
import csv, os, json
import random
import os

class spider1(scrapy.Spider):
    name = "spider1"

    with open("data.csv", "a") as filee:

        if os.stat("data.csv").st_size != 0:
            filee.truncate(0)
        filee.close()

    def start_requests(self):
        list = ["https://www.example.com/item1",
                "https://www.example.com/item2",
                "https://www.example.com/item3",
                "https://www.example.com/item4",
                "https://www.example.com/item5"
                ]

        for i in list:
            yield scrapy.Request(i, callback=self.parse)
            sleep(random.randint(0, 5))

    def parse(self, response):

        product_name = response.css('#pd-h1-cartridge::text')[0].extract()
        product_price = response.css(
            '.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
            '::text')[3].extract()


        with open('data.csv', 'a+') as file:

            itemwriter = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

            itemwriter.writerow([str(product_name).strip(), str(product_price).strip()])

            file.close()
<小时/>

CSV 输出

Purple Wine Glass Cooler,1.47
Color Your Own VBS Island Wind Chimes,6.47
Color Your Own Fuzzy Patriotic Wreaths,7.79
Color Your Own Patriotic Keychains,6.19
Patriotic Cool Treats Craft Stick Magnet Craft Kit,6.19 

最佳答案

仅使用 Scrapy 生成 CSV 文件。

编写一个单独的脚本来比较 CSV 文件。

关于python - 将 CSV 文件记录与 Python Scrapy 输出数据进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56351206/

相关文章:

python - 使用具有不同 xlabel 的 Pandas 绘制日期时间条形图

python - 在 Django 中使用 Ajax 时卡在 View 中

javascript - 获取 csv 文件并读取

python - 将 numpy 数组作为 Pandas 中的列保存/加载到 csv 文件

python-3.x - 抓取 Google 翻译 Python

php - 使用 Simple HTML DOM Parser 按 ID 查找表

python - 大型嵌套列表与字典

python - 将值传递给 Django 表单

python - 合并两个 CSV 列并匹配

python - 如何在 beautifulsoup4 中根据图像内部的内容分离图像链接