需要学习的地方:

1.Scrapy框架流程梳理,各文件的用途等

2.在Scrapy框架中使用MongoDB数据库存储数据

3.提取下一页链接,回调自身函数再次获取数据

重点:从当前页获取下一页的链接,传给函数自身继续发起请求

next = response.css('.pager .next a::attr(href)').extract_first()  # 获取下一页的相对链接
        url = response.urljoin(next)  # 生成完整的下一页链接
        yield scrapy.Request(url=url, callback=self.parse)  # 把下一页的链接回调给自身再次请求

站点:http://quotes.toscrape.com

该站点网页结构比较简单,需要的数据都在div标签中

操作步骤:

1.创建项目

# scrapy startproject quotetutorial

此时目录结构如下:

2.生成爬虫文件

# cd quotetutorial
# scrapy genspider quotes quotes.toscrape.com # 若是有多个爬虫多次操作该命令即可

3.编辑items.py文件,获取需要输出的数据

import scrapy

class QuoteItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
text = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()

4.编辑quotes.py文件,爬取网站数据

# -*- coding: utf-8 -*-
import scrapy from quotetutorial.items import QuoteItem class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com/'] def parse(self, response):
# print(response.status) # 200
quotes = response.css('.quote')
for quote in quotes:
item = QuoteItem() text = quote.css('.text::text').extract_first()
author = quote.css('.author::text').extract_first()
tags = quote.css('.tags .tag::text').extract() item['text'] = text
item['author'] = author
item['tags'] = tags
yield item next = response.css('.pager .next a::attr(href)').extract_first() # 获取下一页的相对链接
url = response.urljoin(next) # 生成完整的下一页链接
yield scrapy.Request(url=url, callback=self.parse) # 把下一页的链接回调给自身再次请求

5.编写pipelines.py文件,进一步处理item数据,保存到mongodb数据库

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html # 使用的话需要在settings文件中设置 import pymongo as pymongo
from scrapy.exceptions import DropItem class TextPipeline(object):
"""对输出的item进行进一步的处理""" def __init__(self):
self.limit = 50 def process_item(self, item, spider):
if item['text']:
if len(item['text']) > self.limit:
item['text'] = item['text'][0:self.limit].rstrip() + '......'
return item
else:
return DropItem('Missing Text!') class MongoPipeline(object):
"""把输出的item保存到MongoDB数据库""" def __init__(self, mongo_url, mongo_db):
self.mongo_uri = mongo_url
self.mongo_db = mongo_db @classmethod
def from_crawler(cls, crawler):
"""从settings文件获取配置信息"""
return cls(
mongo_url=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DB')
) def open_spider(self, spider):
"""初始化mongodb"""
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db] # 为啥用[],而不是() def process_item(self, item, spider):
name = item.__class__.__name__ # 获取item的名称用作表名,也就是QuoteItem
self.db[name].insert(dict(item)) # 为啥要用dict(item)
return item def close_spider(self, spider):
self.client.close()

6.编辑配置文件,增加mongodb数据库参数,以及使用的pipeline管道参数

ITEM_PIPELINES = {
# 'quotetutorial.pipelines.TextPipeline': 300,
'quotetutorial.pipelines.MongoPipeline': 400,
} MONGO_URI = 'localhost'
MONGO_DB = 'quotestutorial'

7.执行程序

# scrapy crawl quotes

8.保存到文件

# scrapy crawl quotes -o quotes.json # 保存成json文件
# scrapy crawl quotes -o quotes.csv # 保存成csv文件
# scrapy crawl quotes -o quotes.xml # 保存成xml文件
# scrapy crawl quotes -o quotes.jl # 保存成jl文件
# scrapy crawl quotes -o quotes.pickle # 保存成pickle文件
# scrapy crawl quotes -o quotes.marshal # 保存成marshal文件
# scrapy crawl quotes -o ftp://user:password@ftp.example.com/path/quotes.csv # 生成csv文件保存到远程FTP上

效果:

源码下载地址:https://files.cnblogs.com/files/sanduzxcvbnm/quotetutorial.7z

Scrapy实战:爬取http://quotes.toscrape.com网站数据的更多相关文章

  1. 简单的scrapy实战:爬取腾讯招聘北京地区的相关招聘信息

    简单的scrapy实战:爬取腾讯招聘北京地区的相关招聘信息 简单的scrapy实战:爬取腾讯招聘北京地区的相关招聘信息 系统环境:Fedora22(昨天已安装scrapy环境) 爬取的开始URL:ht ...

  2. 教程+资源,python scrapy实战爬取知乎最性感妹子的爆照合集(12G)!

    一.出发点: 之前在知乎看到一位大牛(二胖)写的一篇文章:python爬取知乎最受欢迎的妹子(大概题目是这个,具体记不清了),但是这位二胖哥没有给出源码,而我也没用过python,正好顺便学一学,所以 ...

  3. scrapy实战--爬取最新美剧

    现在写一个利用scrapy爬虫框架爬取最新美剧的项目. 准备工作: 目标地址:http://www.meijutt.com/new100.html 爬取项目:美剧名称.状态.电视台.更新时间 1.创建 ...

  4. <scrapy爬虫>爬取quotes.toscrape.com

    1.创建scrapy项目 dos窗口输入: scrapy startproject quote cd quote 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) import ...

  5. Scrapy Learning笔记(四)- Scrapy双向爬取

    摘要:介绍了使用Scrapy进行双向爬取(对付分类信息网站)的方法. 所谓的双向爬取是指以下这种情况,我要对某个生活分类信息的网站进行数据爬取,譬如要爬取租房信息栏目,我在该栏目的索引页看到如下页面, ...

  6. 第三百三十节,web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解

    第三百三十节,web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解 封装模块 #!/usr/bin/env python # -*- coding: utf- ...

  7. 使用scrapy框架爬取自己的博文(2)

    之前写了一篇用scrapy框架爬取自己博文的博客,后来发现对于中文的处理一直有问题- - 显示的时候 [u'python\u4e0b\u722c\u67d0\u4e2a\u7f51\u9875\u76 ...

  8. 如何提高scrapy的爬取效率

    提高scrapy的爬取效率 增加并发: 默认scrapy开启的并发线程为32个,可以适当进行增加.在settings配置文件中修改CONCURRENT_REQUESTS = 100值为100,并发设置 ...

  9. 九 web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解

    封装模块 #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib from urllib import request import j ...

随机推荐

  1. 专注UI——是alert()打败了你!

    在上家公司.常常在页面上写aler()提示代码.没有认为有什么,好寻常.认为提示就本来应该是这种,可是,当我到了这家公司.在測试的时候,由于測试人员看到了一个aler弹出框.结果我的页面被退回重写,后 ...

  2. LeetCode 788. Rotated Digits (旋转数字)

    X is a good number if after rotating each digit individually by 180 degrees, we get a valid number t ...

  3. 排列(permutation) 用1,2,3,…,9组成3个三位数abc,def和ghi,每个数字恰好使用一次,要 求abc:def:ghi=1:2:3。按照“abc def ghi”的格式输出所有解,每行一个解。

    #include <stdio.h> #include <math.h> // 算法竞赛的目标是编程对任意输入均得到正确的结果. // 请先独立完成,如果有困难可以翻阅本书代码 ...

  4. 使用WCF进行跨平台开发之一(WCF的实现、控制台托管与.net平台的调用)

    WCF是Windows Communication Foundation的缩写,是微软发展的一组数据通信的应用程序开发接口,它是.NET框架的一部分,是WinFx的三个重要开发类库之一,其它两个是WP ...

  5. bzoj4872

    期望dp 首先如果k=n的话,那么我们从后往前,只要看到两者的灯就关上,因为如果当前一个灯没关上,那么之后不可能关上,一个灯只能由自己倍数控制,所以这样我们就计算出了需要操作的次数,如果这个次数< ...

  6. phonegap+cordova+ionic调用原生API

    上一篇博客讲了phonegap+cordova+ionic的环境搭建,今天再来分享一篇cordova调用原生API的文章.从技术角度上来讲,这并不是很难,只是有些细节要是没有注意,或者某些步骤不知道的 ...

  7. akka设计模式系列-Backend模式

    上一节我们介绍了Akka使用的基本模式,简单点来说就是,发消息给actor,处理结束后返回消息.但这种模式有个缺陷,就是一旦某个消息处理的比较慢,就会阻塞后面所有消息的处理.那么有没有方法规避这种阻塞 ...

  8. 八皇后问题---详解---参考<<紫书>>

    在一个8*8的棋盘上  放置八个皇后 , 使得他们互相不攻击(皇后攻击范围为 同行同列同对角线) , 方法一 : 从64个格子中 选一个子集 , 使得 " 子集 中恰好有八个元素 , 且任意 ...

  9. RAP接口文档的安装

    本机环境 系统:CentOS 6.7 64 位 MySQL 5.6 JDK 1.8 Tomcat 8 Redis 3.0.7 Rap 0.14.1 Rap 说明 官网:https://github.c ...

  10. [ AHOI 2008 ] Meet

    \(\\\) \(Description\) 一棵\(N\)个节点的树,每条边权都为\(1\). \(M\)组询问,每次给出三个点\(A_i,B_i,C_i\),求从三个点分别出发,移动到同一个点的路 ...