python - 有没有人有 Scrapy 中 sqlite 管道的示例代码?

标签 python sqlite export scrapy

我正在 Scrapy 中寻找 SQLite 管道的一些示例代码。我知道没有内置的支持,但我确信它已经完成了。只有实际的代码才能帮助我,因为我只知道足够的 Python 和 Scrapy 来完成我非常有限的任务,并且需要代码作为起点。

最佳答案

我做了这样的事情:

#
# Author: Jay Vaughan
#
# Pipelines for processing items returned from a scrape.
# Dont forget to add pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/topics/item-pipeline.html
#
from scrapy import log
from pysqlite2 import dbapi2 as sqlite

# This pipeline takes the Item and stuffs it into scrapedata.db
class scrapeDatasqLitePipeline(object):
    def __init__(self):
        # Possible we should be doing this in spider_open instead, but okay
        self.connection = sqlite.connect('./scrapedata.db')
        self.cursor = self.connection.cursor()
        self.cursor.execute('CREATE TABLE IF NOT EXISTS myscrapedata ' \
                    '(id INTEGER PRIMARY KEY, url VARCHAR(80), desc VARCHAR(80))')

    # Take the item and put it in database - do not allow duplicates
    def process_item(self, item, spider):
        self.cursor.execute("select * from myscrapedata where url=?", item['url'])
        result = self.cursor.fetchone()
        if result:
            log.msg("Item already in database: %s" % item, level=log.DEBUG)
        else:
            self.cursor.execute(
                "insert into myscrapedata (url, desc) values (?, ?)",
                    (item['url'][0], item['desc'][0])

            self.connection.commit()

            log.msg("Item stored : " % item, level=log.DEBUG)
        return item

    def handle_error(self, e):
        log.err(e)

关于python - 有没有人有 Scrapy 中 sqlite 管道的示例代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3261858/

相关文章:

python - 是否可以使用 PYQT5 中的元素创建一个类

java - 在 Android 中使用 Fragment 的 SQLite 数据库

sqlite - 使用 DBLinq、SQLite 的代码示例

mysql - 使用 MySQL Workbench CE 导出数据库的数据字典?

java - 简单 jar 文件上出现 NoClassDefFoundError

linux - 在 Linux Bash 中将定义的行复制到另一个文件

python - 在循环中使用 Oct2Py 时关闭 Octave-cli 实例

python - 使用 NLTK 快速删除命名实体

python - 如何检查字典中的值是否都具有相同的值 X?

php - 尝试使用 PHP 处理 SQLite 时,WAMP 中 SQLite 数据库文件的位置?