Python scrapy 持久数据库连接 MySQL

标签 python mysql scrapy

我正在将 scrapy 用于我的一个项目。数据从蜘蛛中抓取并传递到管道以插入数据库。这是我的数据库类代码:

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 数据库中。

from con import Database 

class LinkPipeline(object):

    def __init__(self):
        self.db=Database()

    def process_item(self, item, spider):
        query="""INSERT INTO links (title, location,company_name,posted_date,status,company_id,scraped_link,content,detail_link,job_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s)"""
        params=(item['title'], item['location'], item['company_name'], item['posted_date'], item['status'], item['company_id'], item['scraped_link'], item['content'], item['detail_link'],item['job_id'])
        self.db.insert(query,params)
        return item

从上面的流程中,我感觉到每当通过管道处理 Item 时,就会在 process_item 完成时打开和关闭数据库连接。这会打开太多的数据库连接。我想要一种方法,让我的数据库连接在蜘蛛的整个生命周期中只打开一次,并在蜘蛛关闭时关闭。

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

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

最佳答案

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操作。

class LinkPipeline(object):

    def process_item(self, item, spider):
        query="""INSERT INTO links (title, location,company_name,posted_date,status,company_id,scraped_link,content,detail_link,job_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s)"""
        params=(item['title'], item['location'], item['company_name'], item['posted_date'], item['status'], item['company_id'], item['scraped_link'], item['content'], item['detail_link'],item['job_id'])
        spider.cursor.insert(query,params)
        return item

关于Python scrapy 持久数据库连接 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49750220/

相关文章:

python - Pandas 返回 "Passed header names mismatches usecols"错误

python - 运行 scrapy spider 时出现 Scrapyd init 错误

php - 从 XML-RPC 客户端在 OpenERP/Odoo 上创建潜在客户

python - 如何有效地查找多维数组中相似元素的簇

mysql - 比较MySQL表中同一列的属性

mysql - 如何使用 case 子句创建 sql 请求

python - 无法使用 pip 安装requirements.txt

facebook - 使用 scrapy 从 facebook 中抓取数据

Python - 将线路发送到多个设备(在带有 IP 的文本文件中列出)

php - 如何在php中获取标准输出json