亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從數據庫 scrapy 中檢索數據

從數據庫 scrapy 中檢索數據

在 scrapy 中,我試圖從數據庫中檢索數據,這些數據被蜘蛛抓取并添加到 pipelines.py 中的數據庫中。我想讓這個數據在另一個蜘蛛中使用。具體來說,我想從數據庫中檢索鏈接并在 start_request 函數中使用它。我知道這里也解釋了這個問題Scrapy: Get Start_Urls from Database by Pipeline我試著通過這個例子來做,但不幸的是它不起作用,我不不知道為什么,但我知道我在某個地方犯了錯誤。piplines.pyimport sqlite3class 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()spiderclass 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+'************************')預先感謝您的幫助。
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

管道用于處理項目。如果你想從數據庫中讀取一些東西,打開連接并在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


查看完整回答
反對 回復 2023-01-04
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號