scrapy 爬取到结果后,将结果保存到 sqlite3,有两种方式

  • item Pipeline
  • Feed Exporter

方式一

使用 item Pipeline 有三个步骤

  1. 文件 pipelines.py 中,编写 Sqlite3Pipeline
  2. 文件 settings.py 中,添加 ITEM_PIPELINES
  3. 开始运行爬虫: scrapy crawl example

1. 文件 pipelines.py

说明

参考了官网文档的 MongoDB 的例子

要求

表格 SQLITE_TABLE 要在爬虫运行之前先创建好。否则会报错,原因不详。

代码

import sqlite3

class Sqlite3Pipeline(object):

    def __init__(self, sqlite_file, sqlite_table):
self.sqlite_file = sqlite_file
self.sqlite_table = sqlite_table @classmethod
def from_crawler(cls, crawler):
return cls(
sqlite_file = crawler.settings.get('SQLITE_FILE'), # 从 settings.py 提取
sqlite_table = crawler.settings.get('SQLITE_TABLE', 'items')
) def open_spider(self, spider):
self.conn = sqlite3.connect(self.sqlite_file)
self.cur = self.conn.cursor() def close_spider(self, spider):
self.conn.close() def process_item(self, item, spider):
insert_sql = "insert into {0}({1}) values ({2})".format(self.sqlite_table,
', '.join(item.fields.keys()),
', '.join(['?'] * len(item.fields.keys())))
self.cur.execute(insert_sql, item.fields.values())
self.conn.commit() return item

补充:

Github 有一个使用 twisted 操作 sqlite3 的例子,见这里。请自行对比。

2. 文件 settings.py

激活前面的 Sqlite3Pipeline 类,需要

添加

SQLITE_FILE = 'example.db'
SQLITE_TABLE = 'dmoz' ITEM_PIPELINES = {
'myproject.pipelines.Sqlite3Pipeline': 300,
}

3. 运行爬虫

$ scrapy crawl example

运行效果图:

方式二

使用 Feed Exporter 有三个步骤

  1. 文件 exporters.py 中,编写 Sqlite3ItemExporter
  2. 文件 settings.py 中,添加 FEED_EXPORTERS
  3. 开始运行爬虫: scrapy crawl example -o example.db -t sqlite3

1. 文件 exporters.py

说明

参考了Github的例子,基本没变

代码

from scrapy.exporters import BaseItemExporter
import sqlite3 class Sqlite3ItemExporter(BaseItemExporter): def __init__(self, file, **kwargs):
self._configure(kwargs)
self.conn = sqlite3.connect(file.name)
self.conn.text_factory = str
self.created_tables = [] def export_item(self, item):
item_class_name = type(item).__name__ if item_class_name not in self.created_tables:
keys = None
if hasattr(item.__class__, 'keys'):
sqlite_keys = item.__class__.sqlite_keys
self._create_table(item_class_name, item.fields.iterkeys(), sqlite_keys)
self.created_tables.append(item_class_name) field_list = []
value_list = []
for field_name in item.iterkeys():
field_list.append('[%s]' % field_name)
field = item.fields[field_name]
value_list.append(self.serialize_field(field, field_name, item[field_name])) sql = 'insert or ignore into [%s] (%s) values (%s)' % (item_class_name, ', '.join(field_list), ', '.join(['?' for f in field_list]))
self.conn.execute(sql, value_list)
self.conn.commit() def _create_table(self, table_name, columns, keys = None):
sql = 'create table if not exists [%s] ' % table_name column_define = ['[%s] text' % column for column in columns]
print('type: %s' % type(keys))
if keys:
if len(keys) > 0:
primary_key = 'primary key (%s)' % ', '.join(keys[0])
column_define.append(primary_key) for key in keys[1:]:
column_define.append('unique (%s)' % ', '.join(key)) sql += '(%s)' % ', '.join(column_define) print('sql: %s' % sql)
self.conn.execute(sql)
self.conn.commit() def __del__(self):
self.conn.close()

2. 文件 settings.py

激活前面的 Sqlite3ItemExporter 类,需要

添加


FEED_EXPORTERS = {
'sqlite3': 'myproject.exporters.Sqlite3ItemExporter',
}

3. 运行爬虫

$ scrapy crawl example -o example.db -t sqlite3

说明

第二种方式未测试!

scrapy 保存到 sqlite3的更多相关文章

  1. Python scrapy爬虫数据保存到MySQL数据库

    除将爬取到的信息写入文件中之外,程序也可通过修改 Pipeline 文件将数据保存到数据库中.为了使用数据库来保存爬取到的信息,在 MySQL 的 python 数据库中执行如下 SQL 语句来创建 ...

  2. python scrapy实战糗事百科保存到json文件里

    编写qsbk_spider.py爬虫文件 # -*- coding: utf-8 -*- import scrapy from qsbk.items import QsbkItem from scra ...

  3. 1.scrapy爬取的数据保存到es中

    先建立es的mapping,也就是建立在es中建立一个空的Index,代码如下:执行后就会在es建lagou 这个index.     from datetime import datetime fr ...

  4. Scrapy——將數據保存到MySQL數據庫

    Scrapy--將數據保存到MySQL數據庫 1. 在MySQL中創建數據庫表job_inf: 1 Create table job_inf( 2 id int(11) not null auto_i ...

  5. 使用scrapy爬取的数据保存到CSV文件中,不使用命令

    pipelines.py文件中 import codecs import csv # 保存到CSV文件中 class CsvPipeline(object): def __init__(self): ...

  6. 爬取伯乐在线文章(四)将爬取结果保存到MySQL

    Item Pipeline 当Item在Spider中被收集之后,它将会被传递到Item Pipeline,这些Item Pipeline组件按定义的顺序处理Item. 每个Item Pipeline ...

  7. 将爬取的数据保存到mysql中

    为了把数据保存到mysql费了很多周折,早上再来折腾,终于折腾好了 安装数据库 1.pip install pymysql(根据版本来装) 2.创建数据 打开终端 键入mysql -u root -p ...

  8. 使用官方组件下载图片,保存到MySQL数据库,保存到MongoDB数据库

    需要学习的地方,使用官方组件下载图片的用法,保存item到MySQL数据库 需要提前创建好MySQL数据库,根据item.py文件中的字段信息创建相应的数据表 1.items.py文件 from sc ...

  9. jQuery切换网页皮肤保存到Cookie实例

    效果体验:http://keleyi.com/keleyi/phtml/jqtexiao/25.htm 以下是源代码: <!DOCTYPE html PUBLIC "-//W3C//D ...

随机推荐

  1. 体验最火的敏捷——SCRUM(厦门,2014.1.4)

    1.概述SCRUM是当前最火的一种敏捷开发方法,有用户故事.冲刺.燃尽图等很多很酷的玩法,有牛B的产品负责人.SCRUM Master,有超强的自组织团队.本沙龙将为您展现当前最火最酷的敏捷开发方法! ...

  2. 1.9 基础知识——GP2.10 高级别的领导检查(Higher level management)

    GP2.10 Review the activities,status,and results of XXX process with highter level management and res ...

  3. Eclipse下使用SVN版本控制

    作者:朱先忠编译 转自天极[url]http://dev.yesky.com/356/2578856.shtml[/url] 简单介绍一些基本操作1.同步在Eclipse下,右击你要同步的工程-tea ...

  4. SSH加载顺序问题

    http://bbs.csdn.net/topics/390299835 个人总结 1.项目启动首先加载WEB.xml文件 wen.xml文件中有     <!-- tomcat默认生成的地方是 ...

  5. Symantec Backup Exec备份作业服务器盘符变更

    Symantec Backup Exec的备份作业中,如果某个服务器的磁盘更改了盘符,如果不修改备份作业里面的相关配置,就会出现类似下面的错误信息,如下截图所示 因为这台服务器上我们将原先的G盘的盘符 ...

  6. Xtrabackup数据全备份与快速搭建从服务器

    Percona Xtrabackup可以说是一个完美的数据备份工具.特别是当数据库的容量达到了一定数量级的时候且存在单表达到几十G的数据量, 很难容忍一些逻辑备份的漫长时间.如单个数据库约200G,单 ...

  7. js中同步与异步请求方式

    异步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false, async : true, type : "POST ...

  8. Highcharts使用简例 + 异步动态读取数据

    第一部分:在head之间加载两个JS库. <script src="html/js/jquery.js"></script> <script src= ...

  9. POSIX, Bash, GPL etc

    POSIX , SUS, XSI Portable Operating System Interface POSIX是给Unix/Linux系统使用的通用调用接口(SCI, System Call I ...

  10. ab.exe使用

       ab.exe是一个性能检测工具,是apache server中的一个小组件,使用简单,方便    下载地址:http://files.cnblogs.com/files/gossip/ab.zi ...