[英]Retrieving data from database scrapy
在 scrapy 中,我试图从数据库中检索数据,这些数据被蜘蛛抓取并添加到 pipelines.py 中的数据库中。 我希望这些数据在另一个蜘蛛中使用。 具体来说,我想从数据库中检索链接并在 start_request function中使用它。我知道这个问题在这里也有解释不知道为什么,但我知道我在某个地方犯了错误。
piplines.py
import sqlite3
class HeurekaScraperPipeline:
def __init__(self):
self.create_connection()
self.create_table()
def create_connection(self):
self.conn = sqlite3.connect('shops.db')
self.curr = self.conn.cursor()
def create_table(self):
self.curr.execute("""DROP TABLE IF EXISTS shops_tb""")
self.curr.execute("""create table shops_tb(
product_name text,
shop_name text,
price text,
link text
)""")
def process_item(self, item, spider):
self.store_db(item)
return item
def store_db(self, item):
self.curr.execute("""insert into shops_tb values (?, ?, ?, ?)""",(
item['product_name'],
item['shop_name'],
item['price'],
item['link'],
))
self.conn.commit()
spider
class Shops_spider(scrapy.Spider):
name = 'shops_scraper'
custom_settings = {'DOWNLOAD_DELAY': 1}
def start_requests(self):
db_cursor = HeurekaScraperPipeline().curr
db_cursor.execute("SELECT * FROM shops_tb")
links = db_cursor.fetchall()
for link in links:
url = link[3]
print(url)
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
url = response.request.url
print('********************************'+url+'************************')
提前感谢您的帮助。
管道用于处理项目。 如果您想从数据库中读取某些内容,请打开连接并在start_request
中读取它。 根据文档:
一个项目被蜘蛛抓取后,它被发送到项目管道,该管道通过几个按顺序执行的组件来处理它。
为什么不在 start_request 中打开 DB 连接?
def start_requests(self):
self.conn = sqlite3.connect('shops.db')
self.curr = self.conn.cursor()
self.curr.execute("SELECT * FROM shops_tb")
links = self.curr.fetchall()
# rest of the code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.