将数据存储到 SQL 无法与我的 sql 连接器和 scrapy 一起使用

edl*_*iel 1 python sql mysql-python scrapy

我试图用scrapy将我抓取的数据存储到SQL数据库中,但我的代码在运行时没有提到任何错误,但没有发送任何内容。

我正在使用我的 sql 连接器,因为我无法安装 MySQL-python。我的 SQL 数据库似乎运行良好,当我运行代码时,流量 KB/s 增加。请在我的 pipelines.py 代码下方找到。

import mysql.connector
from mysql.connector import errorcode

class CleaningPipeline(object):
    ...

class DatabasePipeline(object):

    def _init_(self):
        self.create_connection()
        self.create_table()

    def create_connection(self):
        self.conn = mysql.connector.connect(
            host = 'localhost',
            user = 'root',
            passwd = '********',
            database = 'lecturesinparis_db'
        )
        self.curr = self.conn.cursor()

    def create_table(self):
        self.curr.execute("""DROP TABLE IF EXISTS mdl""")
        self.curr.execute("""create table mdl(
                        title text,
                        location text,
                        startdatetime text,
                        lenght text,
                        description text,
                        )""")

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

    def store_db(self, item):
        self.curr.execute("""insert into mdl values (%s,%s,%s,%s,%s)""", (
            item['title'][0],
            item['location'][0],
            item['startdatetime'][0],
            item['lenght'][0],
            item['description'][0],
        ))
        self.conn.commit()
Run Code Online (Sandbox Code Playgroud)

Ahs*_*Roy 5

您需要先添加该类,ITEM_PIPELINES让scrapy 知道我想使用此管道。

在您的settings.py文件中,使用您的类名更新以下行,如下所示。

# https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'projectname.pipelines.CleaningPipeline': 700,
    'projectname.pipelines.DatabasePipeline': 800,
}
Run Code Online (Sandbox Code Playgroud)

数字 700 和 800 显示管道处理数据的顺序,它可以是 1-1000 之间的任何整数。管道将根据此数字按顺序处理项目,因此 700 的管道将在 800 的管道之前处理数据。

注意'projectname.pipelines.CleaningPipeline'用您的实际项目名称替换项目名称。