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. C#生成注册码

    string t = DateTime.Now.Ticks.ToString(); t = DESKey.DESEncrypt(t, DESKey.DesKeyStr); string[] strid ...

  2. mapreduce流程中的几个关键点

    MapReduce中数据流动    (1)最简单的过程:  map - reduce    (2)定制了partitioner以将map的结果送往指定reducer的过程: map - partiti ...

  3. 《CLR via C#》读书笔记--基元类型、引用类型和值类型

    编程语言的基元类型 编译器直接支持的数据类型称为基元类型.基元类型直接映射到Framework类库中存在的类型.例如:C#中的int直接映射到System.Int32类型.下表给出了C#基元类型与对应 ...

  4. java.lang.UnsatisfiedLinkError: Unable to load library 'xxx': Native library (win32-x86-64/ID_Fpr.dll)

    使用 JNA 调用 dll 库,因为 dll 库是32 位的,而 jvm 是 64位的,所以发生的错误: java.lang.UnsatisfiedLinkError: Unable to load ...

  5. 如何在centos上安装epel源

    一.EPEL是什么? EPEL (Extra Packages for Enterprise Linux,企业版Linux的额外软件包) 是Fedora小组维护的一个软件仓库项目,为RHEL/Cent ...

  6. eclipse设置显示代码行数(转)

    (转自:http://jingyan.baidu.com/article/b2c186c89b7023c46ef6ff27.html) 载入eclipse的主页面,默认以英文版的eclipse为例 点 ...

  7. 非常不错的点餐系统应用ios源码完整版

    该源码是一款非常不错的点餐系统应用,应用源码齐全,运行起来非常不错,基本实现了点餐的一些常用的功能,而且界面设计地也很不错,是一个不错的ios应用学习的例子,喜欢的朋友可以下载学习看看,更多ios源码 ...

  8. 虚拟机centos6.5 --安装jdk

    1.首先卸载默认安装的openjdk,如下 rpm -qa | grep java #查看当前是否已经安装了跟java有关的包 yum -y remove java #卸载 rpm -qa |grep ...

  9. 【转】Linux Mint 17.2 gedit中文乱码

    转自:linux mint 14 gedit 中文乱码 Mint默认没安装gconf-editor,搜了下,找到如下解决办法 在终端下执行语句: gconftool- --set --type=lis ...

  10. TCP的关闭,到底是几次握手,每次的标志位到底是什么!

    做题的时候遇到一个问题,TCP关闭的时候到底是三次还是四次握手,如果是三次,少了哪部分?   按照 <计算机网络> -第五版-谢希仁       然而对于TCP关闭, 有的地方能找到   ...