scrapy下使用item才是正经方法。
在item中定义需要保存的内容,然后在pipeline处理item,爬虫流程就成了这样:

抓取 --> 按item规则收集需要数据 -->使用pipeline处理(存储等)

定义item,在items.py中定义抓取内容

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html import scrapy class GetquotesItem(scrapy.Item):
# define the fields for your item here like:
# 定义我们需要抓取的内容:
# 1.名言内容
# 2.作者
# 3.标签
content = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()

我们将数据库的配置信息保存在setting.py文件中,方便调用

MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
MONGODB_DBNAME = 'store_quotes2'
MONGODB_TABLE = 'quotes2'

另外,在setting.py文件中一点要将pipeline注释去掉,要不然pipeline不会起作用:

#ITEM_PIPELINES = {
# 'getquotes.pipelines.SomePipeline': 300,
#}

改成

ITEM_PIPELINES = {
'getquotes.pipelines.GetquotesPipeline': 300,
}

现在在pipeline.py中定义处理item方法:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html # 将setting导入,以使用定义内容
from scrapy.conf import settings
import pymongo class GetquotesPipeline(object): # 连接数据库
def __init__(self): # 获取数据库连接信息
host = settings['MONGODB_HOST']
port = settings['MONGODB_PORT']
dbname = settings['MONGODB_DBNAME']
client = pymongo.MongoClient(host=host, port=port) # 定义数据库
db = client[dbname]
self.table = db[settings['MONGODB_TABLE']] # 处理item
def process_item(self, item, spider):
# 使用dict转换item,然后插入数据库
quote_info = dict(item)
self.table.insert(quote_info)
return item

相应的,myspider.py中的代码变化一下

import scrapy
import pymongo # 别忘了导入定义的item
from getquotes.items import GetquotesItem class myspider(scrapy.Spider): # 设置爬虫名称
name = "get_quotes" # 设置起始网址
start_urls = ['http://quotes.toscrape.com'] '''
# 配置client,默认地址localhost,端口27017
client = pymongo.MongoClient('localhost',27017)
# 创建一个数据库,名称store_quote
db_name = client['store_quotes']
# 创建一个表
quotes_list = db_name['quotes']
'''
def parse(self, response): #使用 css 选择要素进行抓取,如果喜欢用BeautifulSoup之类的也可以
#先定位一整块的quote,在这个网页块下进行作者、名言,标签的抓取
for quote in response.css('.quote'):
'''
# 将页面抓取的数据存入mongodb,使用insert
yield self.quotes_list.insert({
'author' : quote.css('small.author::text').extract_first(),
'tags' : quote.css('div.tags a.tag::text').extract(),
'content' : quote.css('span.text::text').extract_first()
})
'''
item = GetquotesItem()
item['author'] = quote.css('small.author::text').extract_first()
item['content'] = quote.css('span.text::text').extract_first()
item['tags'] = quote.css('div.tags a.tag::text').extract()
yield item # 使用xpath获取next按钮的href属性值
next_href = response.xpath('//li[@class="next"]/a/@href').extract_first()
# 判断next_page的值是否存在
if next_href is not None: # 如果下一页属性值存在,则通过urljoin函数组合下一页的url:
# www.quotes.toscrape.com/page/2
next_page = response.urljoin(next_href) #回调parse处理下一页的url
yield scrapy.Request(next_page,callback=self.parse)

scrapy学习笔记(三):使用item与pipeline保存数据的更多相关文章

  1. scrapy基础知识之将item 通过pipeline保存数据到mysql mongoDB:

    pipelines.py class xxPipeline(object): def process_item(self, item, spider): con=pymysql.connect(hos ...

  2. tensorflow学习笔记(三十四):Saver(保存与加载模型)

    Savertensorflow 中的 Saver 对象是用于 参数保存和恢复的.如何使用呢? 这里介绍了一些基本的用法. 官网中给出了这么一个例子: v1 = tf.Variable(..., nam ...

  3. Scrapy:学习笔记(2)——Scrapy项目

    Scrapy:学习笔记(2)——Scrapy项目 1.创建项目 创建一个Scrapy项目,并将其命名为“demo” scrapy startproject demo cd demo 稍等片刻后,Scr ...

  4. iView学习笔记(三):表格搜索,过滤及隐藏列操作

    iView学习笔记(三):表格搜索,过滤及隐藏某列操作 1.后端准备工作 环境说明 python版本:3.6.6 Django版本:1.11.8 数据库:MariaDB 5.5.60 新建Django ...

  5. openresty 学习笔记三:连接redis和进行相关操作

    openresty 学习笔记三:连接redis和进行相关操作 openresty 因其非阻塞的调用,令服务器拥有高性能高并发,当涉及到数据库操作时,更应该选择有高速读写速度的redis进行数据处理.避 ...

  6. Oracle学习笔记三 SQL命令

    SQL简介 SQL 支持下列类别的命令: 1.数据定义语言(DDL) 2.数据操纵语言(DML) 3.事务控制语言(TCL) 4.数据控制语言(DCL)  

  7. [Firefly引擎][学习笔记三][已完结]所需模块封装

    原地址:http://www.9miao.com/question-15-54671.html 学习笔记一传送门学习笔记二传送门 学习笔记三导读:        笔记三主要就是各个模块的封装了,这里贴 ...

  8. JSP学习笔记(三):简单的Tomcat Web服务器

    注意:每次对Tomcat配置文件进行修改后,必须重启Tomcat 在E盘的DATA文件夹中创建TomcatDemo文件夹,并将Tomcat安装路径下的webapps/ROOT中的WEB-INF文件夹复 ...

  9. java之jvm学习笔记三(Class文件检验器)

    java之jvm学习笔记三(Class文件检验器) 前面的学习我们知道了class文件被类装载器所装载,但是在装载class文件之前或之后,class文件实际上还需要被校验,这就是今天的学习主题,cl ...

随机推荐

  1. sqlplus 格式化一例

    对字符型,用axx格式,对数字型,用9999 格式(999表示占用3列) SQL> col 'ts#' format 999SQL> col 'file#' format 999SQL&g ...

  2. 解决 spring-test 出现 Failed to load ApplicationContext 的异常

    在使用spring-test的时候,在启动@Test的方法时,spring-test会去加载spring的配置文件,这个时候如果配置文件没有在 @ContextConfiguration 中写全,就会 ...

  3. Android中使用MediaCodec硬件解码,高效率得到YUV格式帧,快速保存JPEG图片(不使用OpenGL)(附Demo)

    MediaCodec的使用demo: https://github.com/vecio/MediaCodecDemo https://github.com/taehwandev/MediaCodecE ...

  4. 用Micro:bit控制遥控车

    很多遥控车是用Arduino来控制,同样也可以用Micro:bit来控制.这篇文章我们就来做个测试. 这次需要用到扩展板,管脚比较多,请参考下图 一.材料: •micro:bit 二片 •micro: ...

  5. allure2 report+ jenkins 使用

    物色了一个挺漂亮的报告生成插件 ——allure. 下面介绍一下这个报告的使用. 1. 添加依赖 <dependencies> <!-- https://mvnrepository. ...

  6. Minor GC&Full GC&Major GC区别及触发条件

    Minor GC:从年轻代回收内存 触发条件 1.Eden区域满 ​ 2.新创建的对象大小 > Eden所剩空间 Full GC:清理整个堆空间,包括年轻代和老年代 触发条件 ​ 1.每次晋升到 ...

  7. c#简易学生信息管理系统

    在近期的学习中,我们学习了泛型及泛型集合的概念和使用,泛型是c#中的一个重要概念,为了巩固我们学习的成果,我们可以使用一个实例来进行练习 题目及要求 要求使用Windows窗体应用程序,制作出如上图的 ...

  8. 百度地图在移动端下click无效的解决方案

    这是由于百度地图在移动端屏蔽了click事件,在网上找到一种方法,利用touchClick方法来模拟click事件,代码如下(需要JQ插件): //给jquery添加touchClick方法 (fun ...

  9. CHAPTER 40 Science in Our Digital Age 第40章 我们数字时代的科学

    CHAPTER 40 Science in Our Digital Age 第40章 我们数字时代的科学 The next time you switch on your computer, you ...

  10. impala 使用记录

    在命令行里面直接输入类似下面的语句,就可以执行impala sql语句. impala-shell -q "select * from xxxc limit 10;" 当用pyth ...