Python爬虫进阶(八):Scrapy Tutorial

目录

spiders/spider.py(爬虫文件)

1 start_requests(self)

# 一个不使用start_request开始爬取的方式

2 parse(self,response)

3 其余名词解释

items.py(字段文件)

1 构造Item类

2 使用Item类

pipelines.py(管道文件)

1 process_item(self,item,spider)

2 open_spider(self,spider)

3 close_spider(self,spider)

4 from_crawler(cls,crawler)

5 管道类的配置问题

middlewares.py(中间件文件)

settings.py(配置文件)


Tutorial意为“教程”、“使用说明书”,但本文其实并不能完全地达到这个目的。相比于scrapy完善的doc,本文仅旨在给读者一个基础的关于scrapy的印象,并且为接下来的实例教程打下基础。关于scrapy框架的更深入的学习,还请读者自己努力了。

PS:本节的大部分参考资料来自scrapy官方文档。希望能有英语好的大神翻个中文版,目前网上流传的机翻版本基本上只能起到个聊胜于无的作用。

spiders/spider.py(爬虫文件)

在上一节中我们创建了一个scrapy项目start01,并为其创建了一个爬虫weibo.py。这个文件就是我们题目中的spider.py。

在本文件中,我们需要实现以下几个函数:

1 start_requests(self)

must return an iterable of Requests (you can return a list of requests or write a generator function) which the Spider will begin to crawl from. Subsequent requests will be generated successively from these initial requests.(摘自官方文档)

start_request函数必须返回一个可迭代的Requests对象(你可以返回一个列表或者采用生成器函数),爬虫会从返回的对象url开始爬取。后续请求(url)会从初始请求中生成。

对于其返回的Requests对象中的元素scrapy.http.Request,其生成形如scrapy.http.Request(url,callback),其url为待爬取的链接,callback为爬取完毕后使用的回调函数(解析器)。

# 一个不使用start_request开始爬取的方式

你可以在爬虫类中建立一个名为start_urls的列表,直接将要爬取的链接放入其中,这样scrapy会自动帮你建立请求。在这种情况下,scrapy会对每个请求调用其默认回调函数parse。

2 parse(self,response)

a method that will be called to handle the response downloaded for each of the requests made. The response parameter is an instance of TextResponse that holds the page content and has further helpful methods to handle it.

The parse() method usually parses the response, extracting the scraped data as dicts and also finding new URLs to follow and creating new requests (Request) from them.(摘自官方文档)

parse函数会在为所有请求返回的响应下载时被调用。这些响应的参数是TextResponse的实例,他们保存页面的内容,以供其他方法处理。

(我们要编写的)parse函数通常会解析响应,然后将其中有用的信息组合成字典并且在此之中寻找新的待爬取的url,然后用这些url创建新的请求(并返回给调度器)。

3 其余名词解释

-response.urljoin(url):这个函数在parse中使用,将一个可能是相对链接的链接转换为绝对链接。

-response.follow(url,callback):这个函数能直接构造scrapy.Request,由于其url支持相对连接,可以省掉urljoin。

-response.follow_all(iterurl,callback):这个函数功能与follow相同,其iterurl为一个url iterable。

items.py(字段文件)

在spider一节中,你是否会好奇回调函数返回的字典到了哪里?答案是这里。

The main goal in scraping is to extract structured data from unstructured sources, typically, web pages. Spiders may return the extracted data as items, Python objects that define key-value pairs.

Scrapy supports multiple types of items. When you create an item, you may use whichever type of item you want. When you write code that receives an item, your code should work for any item type.(摘自官方文档)

爬虫会返回从网页中爬取的选取好的数据作为items(也就是形似字典的数据)。scrapy支持多重类型的item类,也就是说你可以返回多种数据类型,比如字典、Item Objects、Dataclass Objects(Python3.7及以后)和Attrs Objects。

对于Item Objects而言,其字段使用scrapy.Field()进行初始化,而scrapy.Field事实上就是python中的字典。所以在生成Field对象时,我们可以传入一些元数据(metadata),比如说使用serializer序列化字段。

1 构造Item类

我们就直接使用Item Objects举例子:

import scrapy

class Start01Item(scrapy.Item):

    # define the fields for your item here like:

    # name = scrapy.Field()

    name=scrapy.Field()

    author=scrapy.Field()

    text=scrapy.Field()

    time=scrapy.Field(serializer=str)

2 使用Item类

一般情况下,Item被实例化之后会提交给pipelines.py,而我们有两种方法来读取Item实例中的数据(对于Item Objects而言)。第一种与对字典的读取方式相同,[key];第二种是get(key,err_message)。在获取不到元素的情况下,第一种方式返回KeyError,第二种方式返回err_message。

pipelines.py(管道文件)

我们在上一节提到,Item在被实例化之后会交给pipeline(管道)处理。

After an item has been scraped by a spider, it is sent to the Item Pipeline which processes it through several components that are executed sequentially.

Each item pipeline component (sometimes referred as just “Item Pipeline”) is a Python class that implements a simple method. They receive an item and perform an action over it, also deciding if the item should continue through the pipeline or be dropped and no longer processed.(摘自官方文档)

item被爬虫实例化之后会被发送到item管道,其通过几个组件来处理item中的数据。每个item管道组件都是一个实现了一些函数的Python类,这些组件会对item执行一些操作并且判断其是否还能被留在管道中。

简而言之,scrapy中的管道承担着清理(冗余数据)、验证(有效性)、检查(重复)、存储的责任,负责数据的进一步规范。

对于每个管道组件类,其可以实现以下函数:

1 process_item(self,item,spider)

这个函数必须被实现。

这个函数会为所有spider爬取出的item调用。其必须返回一个item,或者是一个twisted.internet.defer.deferred,或者抛出一个异常。

2 open_spider(self,spider)

这个函数可以实现。

这个函数在spider被打开时调用。

3 close_spider(self,spider)

这个函数可以实现。

这个函数在spider被关闭时调用。

4 from_crawler(cls,crawler)

这个函数可以实现。

这个函数用于调用scrapy的核心组件。

5 管道类的配置问题

管道必须经过配置才能被scrapy调用,其配置在settings.py中。

在settings.py的ITEM_PIPELINES中以PIPELINENAME:PRIORITY_LEVEL的形式添加一个管道到配置里。其中,PIPELINENAME为你要添加的管道类的名字;PRIORITY_LEVEL为其调用的优先等级,为一个数字,越低调用越优先。

middlewares.py(中间件文件)

本文件不在本教程中讲解,你只要知道他是负责扩展scrapy功能的就可以了。

https://docs.scrapy.org/en/latest/topics/spider-middleware.html

settings.py(配置文件)

顾名思义的配置文件。本文件不在本教程中讲解,想了解更多请看官方文档。

https://docs.scrapy.org/en/latest/topics/settings.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值