Scrapy框架入门

本文详细介绍了Scrapy的原理和组件,包括调度器、下载器、爬虫、实体管道和Scrapy引擎。通过实例演示了Scrapy的安装、项目创建、设置调整、爬虫编写以及数据输出到管道的流程。案例中,爬取了腾讯视频的动漫页面,展示了如何通过调整请求参数实现分页抓取,并利用XPath提取数据。最后,讲解了如何通过管道处理和输出爬取到的数据。
摘要由CSDN通过智能技术生成

一、概述

Scrapy,Python开发的一个快速、高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据。Scrapy用途广泛,可以用于数据挖掘、监测和自动化测试. 其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的, 后台也应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫. Scrapy吸引人的地方在于它是一个框架,任何人都可以根据需求方便的修改。它也提供了多种类型爬虫的基类,如BaseSpider、sitemap爬虫等,最新版本又提供了web2.0爬虫的支持.

二、Scrapy五大基本构成:

Scrapy框架主要由五大组件组成,它们分别是调度器(Scheduler)、下载器(Downloader)、爬虫(Spider)和实体管道(Item Pipeline)、Scrapy引擎(Scrapy Engine)。下面我们分别介绍各个组件的作用。

三、整体架构图

 四、Scrapy安装以及生成项目

scrapy startproject 项目名 scrapy genspider 爬虫名 域名 scrapy crawl 爬虫名

Microsoft Windows [版本 10.0.19043.1586]
(c) Microsoft Corporation。保留所有权利。
 
C:\WINDOWS\system32>scrapy startproject TXmovies
New Scrapy project 'TXmovies', using template directory 'C:\Users\1234\anaconda3\lib\site-packages\scrapy\templates\project', created in:
    C:\WINDOWS\system32\TXmovies
 
You can start your first spider with:
    cd TXmovies
    scrapy genspider example example.com
 
C:\WINDOWS\system32>cd TXmovies
 
C:\Windows\System32\TXmovies>scrapy genspider txms v.qq.com
Created spider 'txms' using template 'basic' in module:
  TXmovies.spiders.txms
 
C:\Windows\System32\TXmovies>

 Scrapy安装

Microsoft Windows [版本 10.0.19043.1586]
(c) Microsoft Corporation。保留所有权利。
 
C:\WINDOWS\system32>python -m pip install --upgrade pip
C:\WINDOWS\system32>pip install wheel
C:\WINDOWS\system32>pip install lxml
C:\WINDOWS\system32>pip install twisted
C:\WINDOWS\system32>pip install pywin32
C:\WINDOWS\system32>pip install scrapy

创建后目录大致页如下

ProjectName              #项目文件夹

ProjectName           #项目目录

items.py               #定义数据结构

middlewares.py    #中间件

pipelines.py          #数据处理

settings.py            #全局配置

spiders              

__init__.py       #爬虫文件

baidu.py

scrapy.cfg               #项目基本配置文件

 

五、案例

1.创建项目

打开一个终端输入(建议放到合适的路径下,默认是C盘)

Microsoft Windows [版本 10.0.19043.1586]
(c) Microsoft Corporation。保留所有权利。
 
C:\WINDOWS\system32>scrapy startproject TXmovies
New Scrapy project 'TXmovies', using template directory 'C:\Users\1234\anaconda3\lib\site-packages\scrapy\templates\project', created in:
    C:\WINDOWS\system32\TXmovies
 
You can start your first spider with:
    cd TXmovies
    scrapy genspider example example.com
 
C:\WINDOWS\system32>cd TXmovies
 
C:\Windows\System32\TXmovies>scrapy genspider txms v.qq.com
Created spider 'txms' using template 'basic' in module:
  TXmovies.spiders.txms
 
C:\Windows\System32\TXmovies>

2.修改setting

ROBOTSTXT_OBEY = False
 
DOWNLOAD_DELAY = 1
 
DEFAULT_REQUEST_HEADERS = {
 
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
 
  'Accept-Language': 'en',
 
  'User-Agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'
 
}
 
 
ITEM_PIPELINES = {
 
   'TXmovies.pipelines.TxmoviesPipeline': 300,
 
}

3.确认要提取的数据,item项

 

# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
 
import scrapy
 
class TxmoviesItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field()
    description = scrapy.Field()

4.写爬虫程序

引入刚刚写好的item,刚刚说了item里面创建的变量就是字典的键值,可以直接进行赋值。赋值后交给管道处理。

简单讲一下这一段代码的思路,首先腾讯视频的url为https://v.qq.com/x/bu/pagesheet/list?append=1&channel=cartoon&iarea=1&listpage=2&offset=0&pagesize=30
我们注意到offset这一项,第一页的offset为0,第二页为30,依次推列。
 

yield

程序里一共有两个yield,我比较喜欢叫它中断,当然中断只在CPU中发生,它的作用是移交控制权,在本程序中,我们对item封装数据后,就调用yield把控制权给管道,管道拿到处理后return返回,又回到该程序。这是对第一个yield的解释。

第二个yield稍微复杂点,这条程序里利用了一个回调机制,即callback,回调的对象是parse,也就是当前方法,通过不断的回调,程序将陷入循环,如果不给程序加条件,就会陷入死循环,如本程序我把if去掉,那就是死循环了。
 

yield scrapy.Request(url=url,callback=self.parse)
 
xpath

还有一个要注意的是如何提取xpathl里的数据,我们的写法有四种,第一种写法拿到selector选择器,也就是原数据,里面有一些我们用不到的东西。第二个extract(),将选择器序列号为字符串。第三个和第四个一样,拿到字符串里的第一个数据,也就是我们要的数据。

items['name']=i.xpath('./a/@title')[0]
items['name']=i.xpath('./a/@title').extract()
items['name']=i.xpath('./a/@title').extract_first()
items['name']=i.xpath('./a/@title').get()
 
 
# -*- coding: utf-8 -*-
 
import scrapy
from ..items import TxmoviesItem
 
class TxmsSpider(scrapy.Spider):
    name = 'txms'
    allowed_domains = ['v.qq.com']
    start_urls = ['https://v.qq.com/x/bu/pagesheet/listappend=1&channel=cartoon&iarea=1&listpage=2&offse=0&pagesize=30']
    offset=0
    def parse(self, response):
        items=TxmoviesItem()
        lists=response.xpath('//div[@class="list_item"]')
        for i in lists:
            items['name']=i.xpath('./a/@title').get()
            items['description']=i.xpath('./div/div/@title').get()
            yield items
        if self.offset < 120:
            self.offset += 30
            url = 'https://v.qq.com/x/bu/pagesheet/listappend=1&channel=cartoon&iarea=1&listpage=2&offset={}&pagesize=30'.format(str(self.offset))
            yield scrapy.Request(url=url,callback=self.parse)

5.交给管道输出

管道可以处理提取的数据,如存数据库。我们这里仅输出。

# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
 
class TxmoviesPipeline(object):
    def process_item(self, item, spider):
        print(item)
        return item

6.run,执行项目

 
from scrapy import cmdline
cmdline.execute('scrapy crawl txms'.split())

7.测试结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值