爬虫入门五(Scrapy架构流程介绍、Scrapy目录结构、Scrapy爬取和解析、Settings相关配置、持久化方案)

本文围绕Scrapy爬虫框架展开,介绍了其架构流程、目录结构,阐述了爬取和解析方法,包括命令、css和xpath解析。还提及通过Settings配置提高爬取效率,以及持久化数据的步骤。此外,讲解了爬虫和下载中间件的使用,集成selenium的步骤、源码去重规则和分布式爬虫等内容。

一、Scrapy架构流程介绍

Scrapy一个开源和协作的框架,其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的,使用它可以以快速、简单、可扩展的方式从网站中提取所需的数据。但目前Scrapy的用途十分广泛,可用于如数据挖掘、监测和自动化测试等领域,也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。

Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架。因此Scrapy使用了一种非阻塞(又名异步)的代码来实现并发。整体架构大致如下:

在这里插入图片描述

官网链接:https://docs.scrapy.org/en/latest/topics/architecture.html

官方原文解释:
1.The data flow in Scrapy is controlled by the execution engine, and goes like this:
	The Engine gets the initial Requests to crawl from the Spider.
(引擎从Spider获取要爬行的初始请求。)
2.The Engine schedules the Requests in the Scheduler and asks for the next Requests to crawl.
(引擎在调度器中对请求进行调度,并要求对下一个请求进行爬取。)
3.The Scheduler returns the next Requests to the Engine.
(调度器将下一个请求返回给引擎。)
4.The Engine sends the Requests to the Downloader, passing through the Downloader Middlewares (see process_request()).
(引擎将请求发送给下载器,通过下载器中间件(请参阅process_request())。)
5.Once the page finishes downloading the Downloader generates a Response (with that page) and sends it to the Engine, passing through the Downloader Middlewares (see process_response()).
(一旦页面完成下载,Downloader就会生成一个响应(使用该页面)并将其发送给引擎,通过Downloader中间件传递(请参阅process_response())。)
6.The Engine receives the Response from the Downloader and sends it to the Spider for processing, passing through the Spider Middleware (see process_spider_input()).
(引擎从下载器接收响应,并通过Spider中间件将其发送给Spider进行处理(参见process_spider_input())。)
7.The Spider processes the Response and returns scraped items and new Requests (to follow) to the Engine, passing through the Spider Middleware (see process_spider_output()).
(Spider处理响应,并通过Spider Middleware(参见process_spider_output())将抓取的项和新的请求返回给引擎。)
8.The Engine sends processed items to Item Pipelines, then send processed Requests to the Scheduler and asks for possible next Requests to crawl.
(引擎将处理过的项目发送到项目管道,然后将处理过的请求发送到调度器,并请求抓取可能的下一个请求。)
9.The process repeats (from step 1) until there are no more requests from the Scheduler.
(该过程重复(从步骤1开始),直到没有来自Scheduler的更多请求。)
	'架构'
	爬虫:spiders(自己定义的,可以有很多),定义起始爬取的地址,解析规则
    引擎:engine ---》控制整个框架数据的流动,大总管
    调度器:scheduler---》要爬取的 requests对象,放在里面,排队,去重
    下载中间件:DownloaderMiddleware---》处理请求对象,处理响应对象,下载中间件,爬虫中间件
    下载器:Downloader ----》负责真正的下载,效率很高,基于twisted的高并发的模型之上
    爬虫中间件:spiderMiddleware----》处于engine和爬虫直接的(用的少)
    管道:piplines---》负责存储数据(管道,持久化,保存,文件,mysql)
	'-----------------'

引擎(EGINE)
	引擎负责控制系统所有组件之间的数据流,并在某些动作发生时触发事件。有关详细信息,请参见上面的数据流部分。

调度器(SCHEDULER)
	用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可以想像成一个URL的优先级队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址

下载器(DOWLOADER)
	用于下载网页内容, 并将网页内容返回给EGINE,下载器是建立在twisted这个高效的异步模型上的

爬虫(SPIDERS)--->在这里写代码
	SPIDERS是开发人员自定义的类,用来解析responses,并且提取items,或者发送新的请求

项目管道(ITEM PIPLINES)
	在items被提取后负责处理它们,主要包括清理、验证、持久化(比如存到数据库)等操作

下载器中间件(Downloader Middlewares)
	位于Scrapy引擎和下载器之间,主要用来处理从EGINE传到DOWLOADER的请求request,已经从DOWNLOADER传到EGINE的响应response,
	你可用该中间件做以下几件事:设置请求头,设置cookie,使用代理,集成selenium

爬虫中间件(Spider Middlewares)
	位于EGINE和SPIDERS之间,主要工作是处理SPIDERS的输入(即responses)和输出(即requests)

二、Scrapy目录结构

myfirstscrapy 			# 项目名
   myfirstscrapy            # 文件夹名字,核心代码,都在这里面
   	spiders            # 爬虫的文件,里面有所有的爬虫
       	__init__.py
       	baidu.py      # 百度爬虫 
       	cnblogs.py    #cnblogs爬虫
       items.py # 有很多模型类---》以后存储的数据,都做成模型类的对象,等同于django的models.py
       middlewares.py # 中间件:爬虫中间件,下载中间件都写在这里面
       pipelines.py   #项目管道---》以后写持久化,都在这里面写
       run.py         # 自己写的,运行爬虫
       settings.py    # 配置文件  django的配置文件
  scrapy.cfg          # 项目上线用的,不需要关注

-以后咱们如果写爬虫,写解析,就写 spiders 下的某个py文件   咱么写的最多的
-以后配置都写在settings 中
-以后想写中间件:middlewares
-以后想做持久化:pipelines,items

三、Scrapy爬取和解析

Scrapy的一些命令

	1 创建项目:scrapy startproject 项目名
	2 创建爬虫:scrapy genspider 爬虫名 爬取的地址
		scrapy gensipder cnblogs www.cnblogs.com
	3 运行爬虫
		运行cnblgos爬虫---》对首页进行爬取
	    scrapy crawl 爬虫名字
	    scrapy crawl cnblogs
	    
	    scrapy crawl cnblogs --nolog  不打印日志
	    
	    
	4 快速运行,不用命令
		项目根路径新建 run.py,写入如下代码,以后右键运行run.py 即可
	    from scrapy.cmdline import execute
		execute(['scrapy', 'crawl', 'cnblogs', '--nolog'])
	    
	    
	    
	5 解析数据---》提供了解析库--》css和xpath
		1 response对象有css方法和xpath方法
	        -css中写css选择器     response.css('')
	        -xpath中写xpath选择   response.xpath('')
	    2 重点1-xpath取文本内容
	        	'.//a[contains(@class,"link-title")]/text()'
	        -xpath取属性
	       	 	'.//a[contains(@class,"link-title")]/@href'
	        -css取文本
	        	'a.link-title::text'
	        -css取属性
	        	'img.image-scale::attr(src)'
	    3 重点2.extract_first()  取一个
	        .extract()        取所有

css解析

import scrapy
class CnblogsSpider(scrapy.Spider):
    name = "cnblogs"
    allowed_domains = ["www.cnblogs.com"]
    start_urls = ["https://www.cnblogs.com"]

    def parse(self, response):
        # response 就是爬取完后的对象
        # print(response.text)
        '使用css解析'
        article_list = response.css('article.post-item')
        for article in article_list:
            title = article.css('a.post-item-title::text').extract_first()
            # 取出所有后单独处理
            desc = article.css('p.post-item-summary::text').extract()
            real_desc = desc[0].replace('\n','').replace(' ','')
            if not real_desc:
                real_desc = desc[1].replace('\n', '').replace(' ', '')
            # print(title)
            # print(real_desc)
            # 作者名字
            author = article.css('footer.post-item-foot>a>span::text').extract_first()
            # print(author)
            # 头像
            image_url = article.css('img.avatar::attr(src)').extract_first()
            # print(image_url)
            # 发布日期
            data = article.css('span.post-meta-item>span::text').extract_first()
            # print(data)
            # 文章地址
            url = article.css('a.post-item-title::attr(href)').extract_first()
            print('''
                文章名:%s
                文章摘要:%s
                文章作者:%s
                作者头像:%s
                文章日期:%s
                文章地址:%s

            '''%(title,real_desc,author,image_url,data,url))

xpath解析

import scrapy
class CnblogsSpider(scrapy
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值