quotes.pyはスパイダーファイルです。パイプラインでsqliteにデータを書き込むときにsqlite db curとconを閉じる最も良い方法
import scrapy
from project.items import ProjectItem
class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com/page/1']
def parse(self, response):
item = ProjectItem()
for quote in response.css('div.quote'):
item['quote'] = quote.css('span.text::text').extract_first()
item['author'] = quote.xpath('span/small/text()').extract_first()
yield item
next_page = response.css('li.next a::attr("href")').extract_first()
if next_page is not None:
yield response.follow(next_page, self.parse)
すべてのページの著者と引用が項目で抽出されました。
以下のpipelines.pyを使用すると、アイテム['author']とアイテム['quote']を/tmp/test.sqlite
に書き込むことができます。
import sqlite3
import json
class ProjectPipeline(object):
def __init__(self):
self.db = r'/tmp/test.sqlite'
self.table = 'data'
self.con = sqlite3.connect(self.db)
self.cur = self.con.cursor()
self.cur.execute("create table {table} (author TEXT,quote TEXT)".format(table=self.table))
def __del__(self):
self.cur.close()
self.con.close()
def process_item(self, item, spider):
self.cur.execute("INSERT INTO {table} VALUES(?,?);".format(table=self.table),(item['author'],item['quote']))
self.con.commit()
return item
scrapy crawl quotes
sipder実行するために、tempary sqliteのファイルtest.sqllite-journal
は常に開かれてcolsed、開かれ、クモの実行時間中に/tmp
ディレクトリを開こうとした時、連続colsed小さな欠点があります。
私はタスクを完了させるためのより良い方法が欲しいです。
1.すべての項目の後にコミットしませんか?
2.すべてのデータを書き込んで閉じます。
なぜすべてのアイテムの後にコミットしていますか? –
どのように作業プロセスをより合理的にするには? –