SQLite3とは
インストール不要で使える手軽なRDBです。Pythonの環境にはデフォルトでインストールされているのでMySQL、PostgreSQLなどの本格DBで試すより、お試しでDB保存などをする場合はこれで十分でしょう。
登録処理
プロジェクト名/プロジェクト名/pipelines.py
pipelinesファイルでscrapyによるスクレイピング実行後に処理を記述します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class SQLitePipeline: def open_spider(self, spider): self.connection = sqlite3.connect('XXX.db') self.c = self.connection.cursor() try: self.c.execute(''' CREATE TABLE テーブル名( title text, name text, ) ''') self.connection.commit() except sqlite3.OperationalError: pass def process_item(self, item, spider): self.c.execute(''' INSERT INTO テーブル名 (title,name) VALUES (?,?) '''),( item.get('title'), item.get('name'), )) self.connection.commit() return item def close_spider(self, spider): self.connection.close() |
「CREATE TABLE」は、2度目以降はエラーになるのでtry exceptで例外処理をするようにします。
settings.py
settings.pyにpipelineの登録をします。
1 2 3 |
ITEM_PIPELINES = { "プロジェクト名.pipelines.SQLitePipeline": 300, } |
データを確認
VSCodeで確認できます。「sqlite」というプラグインを利用します。
XXX.dbというファイルが生成されているのでそれを右クリックで選択してひらけばVSCode上で内容を確認できます。
SELECT文を実行する。
1 2 3 4 5 6 |
import sqlite3 connection = sqlite3.connect('XXX.db') cursor = connection.cursor() for row in cursor.execute('SELECT * FROM テーブル名'): print(row) |
この記事へのコメントはありません。