python - 在 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)
解决方案
推荐阅读
- python - Targets must be 1-dimensional Top_k_categorical_accuracy in Tensorflow
- html - 如何在 Angular 9 中显示多列
- ios - iPadOS:防止 UIContextMenuInteraction 在不使用指针时触发
- database - Neo4J 如何存储数据?
- c++ - 常量引用和引用之间的区别
- java - 如何解决 JSONB 序列化的双向关系?
- c# - .NET Core 中的 Microsoft.Deployment.WindowsInstaller.ProductInstallation.AllProducts 替代方案
- asp.net - 从 Microsoft.Net.Compilers 升级到 Microsoft.Net.Compilers.Toolset
- typeorm - TypeORM:测试我的模型是否与数据库同步
- docker - NMAP 使用 Kubernetes/Docker 显示 GCP 中的所有过滤端口