首页 > 解决方案 > 在 Mysql 中 Scrapy 存储数据

问题描述

目前正在学习Scrapy,想爬取劳力士手表的价格和属性。到目前为止,我的爬虫正在运行并正确显示所有数据。但是,现在我想将爬虫中的数据保存到 mysql 数据库中,但是我遇到了问题。我使用爬虫“Watchbot”获取数据,但是管道没有获取项目。我已经检查了 Settings.py 并启用了管道。我的错误到底在哪里,如何将数据传输到 mysql 数据库?

这是我的名为 Watchbot 的爬虫

import scrapy
from scrapy.crawler import CrawlerProcess
from watches.watches.items import WatchesItem


class WatchbotSpider(scrapy.Spider):
    name = "watchbot"
    start_urls = ["https://www.watch.de/english/rolex.html"]


def parse(self, response, **kwargs):
    for link in response.css("div.product-item-link a::attr(href)"):
        url = link.get()
        yield scrapy.Request(url, callback=self.parse_categories)


def parse_categories(self, response):
    item = WatchesItem()
    item["itemnr"] = response.xpath('//span[@itemprop="sku"]/text()').extract()[0]
    item["reference"] = response.xpath('//span[@itemprop="mpn"]/text()').extract()[0]
    item["year"] = response.xpath(
        '//div[@class="product-option baujahr"]/div[@class="product-option-value"]/text()'
    ).extract()[0]
    yield item

那是 Pipeline.py

import mysql
from watches.watches.spiders import watchbot


class WatchesPipeline(object):
    def __init__(self):
        self.conn = mysql.connector.connect(host="", user="", passwd="", database="")
        self.curr = self.conn.cursor()

    def process_item(self, item, spider):
        self.store_db(item)
        return item

    def store_db(self, item):
        self.curr.execute(
            """insert into watches values (%s), (%s), (%s)""",
            (item["YEAR"][0], item["REFERENCE"][0], item["ITEMNR"][0]),
        )
        self.conn.commit()

那是我的 items.py

import scrapy


class WatchesItem(scrapy.Item):
    year = scrapy.Field()
    itemnr = scrapy.Field()
    reference = scrapy.Field()
    print(itemnr)

标签: pythonmysqldatabasescrapyscrapy-pipeline

解决方案


推荐阅读