我正在将 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/