Python爬虫持续的MySQL数据库连接

2024-04-18 21:17:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的一个项目中使用scrapy。数据从spider抓取并传递到管道中,以便插入数据库。以下是我的数据库类代码:

import MySQLdb


class Database:

    host = 'localhost'
    user = 'root'
    password = 'test123'
    db = 'scraping_db'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db,use_unicode=True, charset="utf8")
        self.cursor = self.connection.cursor()

    def insert(self, query,params):
        try:
            self.cursor.execute(query,params)
            self.connection.commit()
        except Exception as ex:
            self.connection.rollback()


    def __del__(self):
        self.connection.close()

这是我的管道代码,它处理被刮取的项并保存到MySQL数据库中。在

^{pr2}$

从上面的流程中,我感觉到只要通过管道处理项,那么当处理项完成时,数据库连接就会打开和关闭。这将打开太多的数据库连接。我想要一种方式,我的数据库连接在spider的整个生命周期中只打开一次,当spider关闭时关闭。在

我读到spider类中有open_spider和close_spider方法,如果我使用它们,那么如何将对数据库连接的引用从spider的start_requests方法传递到pipeline类?在

有没有更好的方法来解决这个问题?在


Tags: 方法代码self数据库hostdb管道def
1条回答
网友
1楼 · 发布于 2024-04-18 21:17:50
class MySpider(scrapy.Spider):
    name = "myspidername"

    host = 'localhost'
    user = 'root'
    password = 'test123'
    db = 'scraping_db'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db,use_unicode=True, charset="utf8")
        self.cursor = self.connection.cursor()

    def insert(self, query,params):
        try:
            self.cursor.execute(query,params)
            self.connection.commit()
        except Exception as ex:
            self.connection.rollback()


    def __del__(self):
        self.connection.close()

然后在管道中执行此操作spider.cursor,以访问cursor并执行任何MySQL操作。在

^{pr2}$

相关问题 更多 >