Scrapy网络爬虫基础

ops/2025/2/11 20:56:29/

使用Spider提取数据

Scarpy网络爬虫编程的核心就是爬虫Spider组件,它其实是一个继承与Spider的类,主要功能设计封装一个发送给网站服务器的HTTP请求,解析网站返回的网页及提取数据

执行步骤

1、Spider生成初始页面请求(封装于Request对象中),提交给引擎
2、引擎通知下载按照Request的要求,下载网页文档,再将文档封装成Response对象作为参数传回给Spider
3、Spider解析Response中的网页内容,生成结构化数据Item,或者产生新的请求(比如爬取下一页),再次发送给引擎
4、如果发送给引擎的是新的Request,就继续第2步。如果发送的是结构化数据Item,则引擎通知其他组件处理该数据(保存的文件或数据库中)

class DingdianXuanhuanSpider(scrapy.Spider):# 爬虫名称name = "dingdian_xuanhuan"# 允许的域名allowed_domains = ["www.xiaoshuopu.com"]# 起始URL列表start_urls = ["https://www.xiaoshuopu.com/class_1/"]def parse(self, response):# 小说列表novel_list = response.xpath("//table/tr[@bgcolor='#FFFFFF']")print("小说数量是:", len(novel_list))# 循环获取小说名称、最新章节、作者、字数、更新、状态for novel in novel_list:# 小说名称name = novel.xpath("./td[1]/a[2]/text()").extract_first()# 最新章节new_chapter = novel.xpath("./td[2]/a/text()").extract_first()# 作者author = novel.xpath("./td[3]/text()").extract_first()# 字数word_count = novel.xpath("./td[4]/text()").extract_first()# 更新update_time = novel.xpath("./td[5]/text()").extract_first()# 状态status = novel.xpath("./td[6]/text()").extract_first()# 将小说内容保存到字典中novel_info = {"name": name,"new_chapter": new_chapter,"author": author,"word_count": word_count,"update_time": update_time,"status": status}print("小说信息:",novel_info)# 使用yield返回数据yield novel_info
  • name:必填项,用于区分不同的爬虫。一个Scrapy项目中可以有多个爬虫。不同的爬虫name值不能相同
  • start_urls:存放要爬取的模板网页地址的列表
  • start_request()爬虫启动时,引擎自动调用该方法,并且只会被调用一次,用于生成初始的请求对象,代码中没有是因为直接使用了基类的功能
  • parse():Spider类的核心方法。引擎将下载好的页面作为参数传递给parse方法,parse方法执行从页面中解析数据的功能

重写start_request方法

如何避免爬虫被网站识别出来导致被禁用呢?
通过重写start_request方法,手动生成一个功能更强大的Request对象。伪装浏览器、自动登录等功能都是在Request对象中设置的

  • 爬虫伪装成浏览器
  • 设置新的解析数据的回调函数,不使用默认的parse()
class QdYuepiaoSpider(scrapy.Spider):name = "qd_yuepiao"allowed_domains = ["www.qidian.com"]start_urls = ["https://www.qidian.com/rank/yuepiao/"]# 设置代理headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"}# 重写请求def start_requests(self):for url in self.start_urls:yield scrapy.Request(url=url, headers=self.headers, callback=self.parse)def parse(self, response):print("数据:", response.xpath("//div"))

注:上面简单设置headers还是会被一些反爬的网站给识别出来。

更好的方式是在settings中启用并设置user-agent,这样项目下的所用爬虫都能使用到该设置
在这里插入图片描述

USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"

Request对象

request对象用来描述一个HTTP请求,它通常在Spider中生成并由下载器执行

class Request(url: str,callback: ((...) -> Any) | None = None,method: str = "GET",headers: dict | None = None,body: bytes | str | None = None,cookies: dict | List[dict] | None = None,meta: dict | None = None,encoding: str = "utf-8",priority: int = 0,dont_filter: bool = False,errback: ((...) -> Any) | None = None,flags: List[str] | None = None,cb_kwargs: dict | None = None
)
  • url :HTTP请求的网址
  • callback:指定回调函数,即确定页面的解析函数,默认为parse。在解析期间如果发生异常会调用errback
  • method:请求方式。默认为GET,必须大写英文字母
  • headers:HTTP请求头
  • body:HTTP请求体
  • cookies:请求的Cookie值,可以实现自动登录的效果
  • meta:字典类型,用于数据的传递,可以将数据传递给其他组件,也可以传递给Response对象
  • encoding:请求的编码方式。默认UTF-8
  • priority:请求的优先级,优先级高的优先下载
  • dont_filter:默认值为False,避免对同一个url的重复请求。设置True,即使是重复的请求也会强制下载
  • errback:在处理请求时引发任何异常时调用的函数

多页数据爬取
大多数网站都会存在分页条,进行多个页面数据爬取需要:

在解析函数中,提取完本页数据并提交给引擎后,设法提取到下一页的URL地址,使用这个地址生成新的请求对象,再提交给引擎。

import scrapyclass DangaoSpider(scrapy.Spider):name = "dangao"allowed_domains = ["sc.chinaz.com"]start_urls = ["https://sc.chinaz.com/tupian/dangaotupian.html"]def parse(self, response):# 定位到图片的元素,并保存到列表中img_list = response.xpath("//div[@class='item']/img")for img in img_list:name = img.xpath("./@alt").extract_first()src = img.xpath("./@data-original").extract_first()img_info = {"name": name, "src": src}yield img_info# 获取下一页的urlnext_url = response.xpath("//a[@class='nextpage']/@href").extract_first()if next_url != None:next_url = "https://sc.chinaz.com/tupian/" + next_urlprint("下一页地址是:", next_url)# 生成新的请求对象,并交给引擎执行yield scrapy.Request(url=next_url, callback=self.parse)

在这里插入图片描述

使用Item封装数据

Item对象是一个简单的容器,用于收集抓取到的数据,其提供了类似于字典的API,并具有用于声明可用字段的简单语法

定义Item 和 Field
items.py中创建对应的类

class DingdianItem(scrapy.Item):# 小说名称、作者、最新、字数、更新时间、状态name = scrapy.Field()author = scrapy.Field()new_chapter = scrapy.Field()word_count = scrapy.Field()update_time = scrapy.Field()status = scrapy.Field()

在相应爬虫中使用

import scrapy
from qidian_yuepiao.items import DingdianItemclass DingdianXuanhuanSpider(scrapy.Spider):# 爬虫名称name = "dingdian_xuanhuan"# 允许的域名allowed_domains = ["www.xiaoshuopu.com"]# 起始URL列表start_urls = ["https://www.xiaoshuopu.com/class_1/"]def parse(self, response):# 小说列表novel_list = response.xpath("//table/tr[@bgcolor='#FFFFFF']")print("小说数量是:", len(novel_list))# 循环获取小说名称、最新章节、作者、字数、更新、状态for novel in novel_list:# 小说名称name = novel.xpath("./td[1]/a[2]/text()").extract_first()# 最新章节new_chapter = novel.xpath("./td[2]/a/text()").extract_first()# 作者author = novel.xpath("./td[3]/text()").extract_first()# 字数word_count = novel.xpath("./td[4]/text()").extract_first()# 更新update_time = novel.xpath("./td[5]/text()").extract_first()# 状态status = novel.xpath("./td[6]/text()").extract_first()# 将小说内容保存到Item中novel_info = DingdianItem()novel_info["name"] = namenovel_info["new_chapter"] = new_chapternovel_info["author"] = authornovel_info["word_count"] = word_countnovel_info["update_time"] = update_timenovel_info["status"] = statusprint("小说信息:", novel_info)# 使用yield返回数据yield novel_info

在这里插入图片描述

使用ItemLoader填充容器

在项目很大、提取的字段数很多时,数据提取规则也会越来越多,再加上还要对提取到的数据做转换处理,代码就会变得臃肿,维护起来困难。

为了解决这个问题,Scrapy提供了项目加载器(ItemLoader)这样一个填充容器。通过填充容器,可以配置Item中各个字段的提取规则,并通过函数分析原始数据,最后进行赋值

ItemItemLoader 的区别在于:

Item提供了保存数据的容器,需要手动将数据保存于容器中
ItemLoader提供的是填充容器的机制,提供了3种方法

  • add_xpath:使用xpath选择器提取数据
  • add_css:使用css选择器提取数据
  • add_value:直接传值
import scrapy
from qidian_yuepiao.items import DingdianItem
from scrapy.loader import ItemLoaderclass DingdianXuanhuanSpider(scrapy.Spider):# 爬虫名称name = "dingdian_xuanhuan"# 允许的域名allowed_domains = ["www.xiaoshuopu.com"]# 起始URL列表start_urls = ["https://www.xiaoshuopu.com/class_1/"]def parse(self, response):# 小说列表novel_list = response.xpath("//table/tr[@bgcolor='#FFFFFF']")print("小说数量是:", len(novel_list))# 循环获取小说名称、最新章节、作者、字数、更新、状态for novel in novel_list:# 生成ItemLoader对象novel_info = ItemLoader(item=DingdianItem(),selector=novel)# 小说名称novel_info.add_xpath("name","./td[1]/a[2]/text()")# 最新章节novel_info.add_xpath("author","./td[2]/a/text()")# 作者novel_info.add_xpath("new_chapter","./td[3]/text()")# 字数novel_info.add_xpath("word_count","./td[4]/text()")# 更新novel_info.add_xpath("update_time","./td[5]/text()")# 状态novel_info.add_xpath("status","./td[6]/text()")print("小说信息:", novel_info)

处理数据
使用ItemLoader提取出的数据也是保存于列表中,以前可以通过extract_first()获取列表数据,现在呢?需要使用输入处理器input_processor和输出处理器out_processor

import scrapy
from scrapy.loader.processors import TakeFirstclass DingdianItem(scrapy.Item):# 定义一个转换函数def change_status(status):if status[0] == "连载中":return 1else:return 2# 小说名称、作者、最新、字数、更新时间、状态# 使用内置函数,获取列表中第一个非空数据name = scrapy.Field(output_processor=TakeFirst)author = scrapy.Field(output_processor=TakeFirst)new_chapter = scrapy.Field(output_processor=TakeFirst)word_count = scrapy.Field(output_processor=TakeFirst)update_time = scrapy.Field(output_processor=TakeFirst)status = scrapy.Field(input_processor=change_status, output_processor=TakeFirst)

使用Pipeline封装数据

Spider将收集的数据封装成Item后,将会被传递到Item Pipeline 项目管道组件中等待进一步处理。Scrapy犹如一个爬虫流水线,Item Pipeline是流水线的最后一道工序,它是可选的,默认关闭,使用时需要将它激活。如果需要,也可以定义多个 Item Pipeline组件,数据会依次访问每个组件,执行相应的数据处理功能

典型应用

  • 清理数据
  • 验证数据的有效性
  • 查重并丢弃
  • 将数据按照自定义的格式存储到文件中
  • 将数据保存的数据库中

当创建项目后,会字段生成一个pipelines.py文件,在里面编写自己的Item Pipeline

# 默认生成的
class QidianYuepiaoPipeline:# process_item 是必须实现的,用于处理每一条数据Item# item 是待处理的Item对象,spider是爬取此数据的spider对象def process_item(self, item, spider):# 编写相应的处理逻辑if item["status"] == 1:item["status"] = "连载"else:item["status"] = "完结"return item# 自定义的
class DingdianPipeline:def __init__(self):# 类初始化函数passdef process_item(self, item, spider):# 编写相应的处理逻辑item["status"] = item["status"].replace("连载", "1").replace("完结", "2")return item

启用 Item Pipeline
在配置文件settings.py中启用被注释掉的代码

ITEM_PIPELINES = {"qidian_yuepiao.pipelines.DingdianItemPipeline": 100,"qidian_yuepiao.pipelines.QidianYuepiaoPipeline": 300,
}

格式为项目名.pipelines.对应的类:优先级,数值越小优先级越高。在settings.py中设置后会对所有爬虫都生效。如果想针对每一个爬虫使用某一个,可以在爬虫内部进行指定,例如

class ScrapyASpider(scrapy.Spider):name = 'scrapyA'custom_settings = {'ITEM_PIPELINES': {'myproject.pipelines.MyCustomPipelineForScrapyA': 300,# 其他可能需要的Pipelines...},}# 爬虫的具体逻辑...

保存为其他文件

# 默认生成的
class QidianYuepiaoPipeline:# 文件名称file_name = datetime.now().strftime("%Y%m%d%H%M%S") + ".txt"# 文件对象file = None# Spider开启时,执行打开文件操作def open_spider(self, spider):# 以追加形式打开文件self.file = open(self.file_name, "a", encoding="utf-8")# process_item 是必须实现的,用于处理每一条数据Item# item 是待处理的Item对象,spider是爬取此数据的spider对象def process_item(self, item, spider):# 写入文件self.file.write("名称:"+item["name"] + "\n")return item# 爬虫关闭时,执行关闭文件操作def close_spider(self, spider):self.file.close()

在这里插入图片描述

案例

还是以获取上面获取蛋糕的案例为基础,上面我们获取了蛋糕图片的名称和地址,我们再次基础上获取图片的简介内容

import scrapy
from scarpy_study.items import DanGaoItemclass DangaoSpider(scrapy.Spider):name = "dangao"allowed_domains = ["sc.chinaz.com"]start_urls = ["https://sc.chinaz.com/tupian/dangaotupian.html"]def parse(self, response):# 定位到图片的元素,并保存到列表中img_list = response.xpath("//div[@class='item']")for img_item in img_list:# 获取图片名称和图片地址name = img_item.xpath("./img/@alt").extract_first()src = img_item.xpath("./img/@data-original").extract_first()img_info = {"name": name,"url": src}# 获取图片详情地址detail_url = img_item.xpath("./div[@class='bot-div']/a/@href").extract_first()# print("详情地址:", detail_url)if detail_url != None:detail_url = 'https://sc.chinaz.com' + detail_url# 生成新的请求,并使用meta传递信息yield scrapy.Request(url=detail_url, callback=self.parse_detail,meta={"img_info": img_info})# 获取下一页的urlnext_url = response.xpath("//a[@class='nextpage']/@href").extract_first()if next_url != None:next_url = "https://sc.chinaz.com/tupian/" + next_urlprint("下一页地址是:", next_url)# 生成新的请求对象,并交给引擎执行yield scrapy.Request(url=next_url, callback=self.parse)# 用来解析详情页def parse_detail(self, response):img_info = response.meta["img_info"]print("img_info:", img_info)# 记录图片的名称、地址dangaoItem = DanGaoItem()dangaoItem["name"] = img_info["name"]dangaoItem["url"] = img_info["url"]# 获取描述desc = response.xpath("//p[@class='all-c']/text()").extract_first()dangaoItem["desc"] = descprint("蛋糕图片信息:", dangaoItem)yield dangaoItem

这里获取详情的核心是,在生成新的请求对象时使用callback指定详情信息的解析函数,使用meta来传递之前获取到的图片名称和图片地址

# 生成新的请求,并使用meta传递信息yield scrapy.Request(url=detail_url, callback=self.parse_detail,meta={"img_info": img_info})

在这里插入图片描述


http://www.ppmy.cn/ops/124104.html

相关文章

刷c语言练习题6(牛客网)

1、下面函数的功能是( ) 1 2 3 4 5 6 int sss(char s[], char t[]) { int i 0; while(s[i] && t[i] && (t[i] s[i])) i; return (s[i] - t[i]); } A、求字符串的长度 B、比较两个字符串的大小 C、将字符串s复制到字符串…

从开发效率到查询性能:JPA 和 MyBatis 在企业系统中的完美结合

1. 为什么选择 JPA 处理单据? 单据类操作通常包括创建、更新、删除、查询(增删改查)等操作。这些操作对于系统的正确性和稳定性至关重要,而 JPA 提供的优雅封装和一致性控制正好符合这些需求。 1.1 JPA 的缓存和延迟加载 JPA 提…

正则表达式-入门

什么是正则表达式 正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。 正则表达式是对字符串执行模式匹配的技术 快速入…

c# 可空引用类型

在 C# 8 中,引入了可空引用类型(Nullable Reference Types,NRT),这是一项增强特性,旨在提高代码的安全性并减少运行时的 NullReferenceException。以下是关于可空引用类型的详细讲解。 什么是可空引用类型…

【RPC】—Thrift协议 VS Protobuf

Thrift协议 & VS Protobuf ⭐⭐⭐⭐⭐⭐ Github主页👉https://github.com/A-BigTree 笔记仓库👉https://github.com/A-BigTree/tree-learning-notes 个人主页👉https://www.abigtree.top ⭐⭐⭐⭐⭐⭐ 文章目录 Thrift协议 & VS Pro…

springboot系列--web相关知识探索三

一、前言 web相关知识探索二中研究了请求是如何映射到具体接口(方法)中的,本次文章主要研究请求中所带的参数是如何映射到接口参数中的,也即请求参数如何与接口参数绑定。主要有四种、分别是注解方式、Servlet API方式、复杂参数、…

数据结构--List的介绍

目录 1. 什么是List Collection中有那些方法? add(E e)方法 addAll(Collection c)方法 clear()方法 contains(Object o)方法 containsAll(Collection c)方法 equals(Object o)方法 hashCode()方法 isEmpty()方法 iterator()方法 remove(Object o)方法 …

【最新华为OD机试E卷-支持在线评测】补种未成活胡杨(100分)多语言题解-(Python/C/JavaScript/Java/Cpp)

🍭 大家好这里是春秋招笔试突围 ,一枚热爱算法的程序员 💻 ACM金牌🏅️团队 | 大厂实习经历 | 多年算法竞赛经历 ✨ 本系列打算持续跟新华为OD-E/D卷的多语言AC题解 🧩 大部分包含 Python / C / Javascript / Java / Cpp 多语言代码 👏 感谢大家的订阅➕ 和 喜欢�…