scrpay爬虫框架
一、初窥Scrapy
Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。
其最初是为了 页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。
二、Scrapy框架运行原理
1. 组件解释
- Spiders:
爬虫类,负责数据初始化,编写爬取网站的url,数据解析等。 - Scrapy Engine:
中心引擎,负责数据流的执行,将爬虫类中定义的 url 推向调度器(Scheduler)。 - Scheduler:
调度器,负责将爬取请求安排进请求队列。 - Downloader:
下载器,负责根据爬虫定义的 url 进行下载数据。 - Items:
封装爬虫返回体中的数据格式,类似于java中的业务VO类。 - Item Pipeline:
数据管道,爬取到的数据在此进行处理,主要有数据过滤,去重,存储等操作。 - Spider Middlewares 和 Downloader Middlewares:
中间件,在此负责做一些截获操作等。
2. 爬虫运行顺序:
上图中箭头代表 Scrapy 框架的运行顺序,起点为Spider,分别经过 Scrapy Engine,Scheduler,Downloader,Spider,Item Pipeline,最后结束爬虫整个过程。
下面举例说明爬虫的运行顺序,如待爬取网站的 url 为 url_A:
- Spiders: 负责做数据初始化,定义准备爬取网站的 url 地址, 如 url_A
- Engine:引擎将 url-A 推向调度器
- Schedule:调度器将 url_A 交给 downbader 进行下载
- Downloader: 下载器根据 url-A 进行下载数据,下载好的数据 data_A 交给 Spiders
- Spiders:将爬取的数据 data_A 进行解析,如将数据据处理成 data_process
- Item Pipeline:对解析后的数据 data_process 进行过滤存储等。
三、Scrapy 框架使用
- 框架安装:
pip install scrapy
# 或者
conda install scrapy
- Scrapy 基础命令:
Scrapy命令分为两种:全局命令和项目命令(使用Scrapy -h可以查看)-
全局命令:在哪都可以使用
-
项目命令:必须在爬虫项目(Scrpay项目)中才能使用。
-
Scrapy常用命令有:
-
scrapy startproject <project_name> #在当前目录下创建一个名为 <project_name>的爬虫项目
scrapy genspider <name> <domain> # 在当前项目中创建spider类
scrapy runspider <spider_file.py> # 运行一个爬虫spider类文件
scrapy list # 列出当前项目中所有可用的spider。每行输出一个spider。
scrapy crawl <spider_name> # 通过名称来运行指定的爬虫
scrapy shell [url/文件名] # 使用shell进入scrapy交互环境
四、实例演示
如我们需要爬取如下网站的信息,网站链接为:https://fang.5i5j.com
爬取网站中的楼盘列表信息为例:
-
新建Scrapy项目:
scrapy startproject demo -
新建爬虫:
scrapy genspider fang fang.5i5j.com
以上两条命令需要在cmd窗口中执行:
新建好的 Scrapy 项目 demo:
新建好的爬虫类:
默认的 Scrapy 项目的目录结构:
一般用户只需要写:Spiders,items.py,piplines.py
偶尔再写一下中间件:Downloader Middlewares,Spider Middlewares
下面是代码部分:
3. 编辑爬虫类,即fang.py文件:
# -*- coding: utf-8 -*-
import scrapy
from demo.items import FangItem
class FangSpider(scrapy.Spider):
# 唯一标识(项目中可能会存在多个爬虫)
name = 'fang'
# 允许访问的域名
allowed_domains = ['fang.5i5j.com']
# 当前爬取的第一个url地址,可以用逗号拼接多个地址
start_urls = ['https://fang.5i5j.com/bj/loupan/']
# 爬取结束调用的方法
def parse(self, response):
print(response.status)
hlist = response.css("li.houst_ctn")
print("房屋信息:")
for vo in hlist:
item = FangItem()
item['title'] = vo.css("span.house_name ::text").extract_first()
item['address'] = vo.css("span.tag_icon_site left").extract_first()
item['time'] = vo.re("(.*?)日开盘")
item['price'] = vo.css("p.price").extract_first()
# 将数据送到pipelines管道
yield item
# pass
- 编辑 items.py(创建Item的数据结构):
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
# 定义返回数据的封装
class FangItem(scrapy.Item):
# define the fields for your item here like:
title = scrapy.Field()
address = scrapy.Field()
time = scrapy.Field()
price = scrapy.Field()
# pass
- 编辑pipelines.py(默认即可):
# -*- 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
class DemoPipeline(object):
def process_item(self, item, spider):
return item
-
在 settings.py 打开 item_pipeline:(取消前面的注释即可)
以上代码中关键点有如下:-
爬虫类文件中,既有定义爬取的 url 等,又有解析爬取的数据,def parse(self, response),爬取的结果在response中,parse是结果解析函数
-
爬虫类文件中 parse 的函数内解析数据,需要一点前端DOM元素的知识,如:
hlist = response.css(“li.houst_ctn”)解析当前网页中 “<li>” 标签中样式为 houst_ctn 的元素。
解析需要的数据方法为:通过鼠标右键检查元素,选到需要解析的数据位置,查看这个数据的标签,然后解析即可。如下图:
-
yield item:负责将数据传输到 pipelines.py 管道中。
-
-
执行爬虫:
scrapy crawl fang
可以在cmd窗口中,也可以在编译器的终端中执行如上的命令,效果如下图:
-
同时也可以将爬取到的数据存储到文件中,格式支持:json,csv,xml,pickle,marshal等。
命令如下:
scrapy crawl fang -o fangs.json
scrapy crawl fang -o fangs.csv
scrapy crawl fang -o fangs.xml
scrapy crawl fang -o fangs.pickle
scrapy crawl fang -o fangs.marshal
完整代码见github:
https://github.com/pentiumCM/scrapy_learn