Scrapy框架初识及入门

178 阅读2分钟

为什么要学习Scrapy

图片.png

什么是Scrapy

Scrapy是⼀个为了爬取⽹站数据,提取结构性数据⽽编写的应⽤框架,我们只需要实现少量的代码,就能够快速的抓取

Scrapy使⽤了Twisted异步⽹络框架,可以加快我们的下载速度

参考网站:github.com/scrapy/scra…

scrapy.org/

docs.scrapy.org/en/latest/

阻塞和非阻塞的区别

图片.png 异步:调⽤在发出之后,这个调⽤就直接返回,不管有⽆结果

⾮阻塞:关注的是程序在等待调⽤结果时的状态,指在不能⽴刻得到结果之前,该调⽤不会阻塞当前线程。

Scrapy工作流程

基本的爬虫流程:

图片.png

另外一种爬虫方式:

图片.png

Scrapy的爬虫流程

图片.png

Scrapy engine(引擎)总指挥:负责数据和信号在不同模块间的传递Scrapy已经实现
Scheduler(调度器)一个队列,存放引擎发过来的request请求Scrapy已经实现
Downloader(下载器)下载吧引擎发过来的requests请求,并返回给引擎Scrapy已经实现
Spider(爬虫)处理引擎发来的response,提取数据,提取url,并交给引擎需要手写
Item Pipline(管道)处理引擎传过来的数据,比如存储需要手写
Downloader Middlewares(下载中间件)可以自定义的下载扩展,比如设置代理
Spider Middlewares(中间件)可以自定义requests请求和进行response过滤一般不用手写

Scrapy

创建一个scrapy项目

scrapy startproject mySpider

图片.png

生成一个爬虫

scrapy genspider demo "demo.cn"
PS E:\Study\code\Python\网络爬虫\ScrapyStudy> cd .\mySpider\
PS E:\Study\code\Python\网络爬虫\ScrapyStudy\mySpider> ls


    Directory: E:\Study\code\Python\网络爬虫\ScrapyStudy\mySpider


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        11/11/2024     19:15                mySpider
-a----        11/11/2024     19:15            270 scrapy.cfg


PS E:\Study\code\Python\网络爬虫\ScrapyStudy\mySpider> dir


    Directory: E:\Study\code\Python\网络爬虫\ScrapyStudy\mySpider


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        11/11/2024     19:15                mySpider
-a----        11/11/2024     19:15            270 scrapy.cfg


PS E:\Study\code\Python\网络爬虫\ScrapyStudy\mySpider> pwd

Path
----
E:\Study\code\Python\网络爬虫\ScrapyStudy\mySpider


PS E:\Study\code\Python\网络爬虫\ScrapyStudy\mySpider>scrapy genspider xl news.sina.com.cn
Created spider 'xl' using template 'basic' in module:
  mySpider.spiders.xl
PS E:\Study\code\Python\网络爬虫\ScrapyStudy\mySpider>

图片.png

提取数据

完善spider 使用xpath

xl.py文件中添加以下代码进行测试

print("="*30)  
print(response)  
print(type(response))  
print("="*30)

图片.png

现在,正式重新写xpath来获取网页信息

li_list = response.xpath("//div[@class='main-nav']//ul/li/a/text()")  
print("获取到:{}个标题".format(len(li_list)))  
print(type(li_list))  
for li in li_list:  
print(li.extract())

运行程序:

图片.png

Scrapy运行

在命令行中运行爬虫

scrapy srawl xl # xl 爬虫的名字

运行成功

图片.png

在Pycharm中爬虫

from scrapy import cmdline  
  
# 方法1  
cmdline.execute("scrapy crawl xl".split())  
  
# 方法2  
# cmdline.execute(["scrapy", "crawl", "xl"])

图片.png

关闭程序运行中的中间件信息

图片.png

进入settings.py添加一行日志代码

LOG_LEVEL ="WARNING"

图片.png

启动scrapy程序查看一下,

图片.png

可以看到,没有任何的中间件信息了