scrapy阅读笔记(一):创建spider,继承scrapy.Spider

最近打算深入学习 scrapy 然后整理了一些官方文档以及爬虫源码的相关笔记写在这供自己和大家一起参考

我们创建一个爬虫后首先是要继承scrapy.Spider,为什么要继承这个基类
官方文档是这么说的:

They must subclass scrapy.Spider and define the initial requests to make

我们必须继承scrapy.Spider这个基类 然后定义初始化的请求.

还是有些糊涂 在查看了官方的源码以后发现 官方的注释是

Base class for scrapy spiders. All spiders must inherit from this
class.

所有的scrapy爬虫都必须得继承这个类。

一个简单的爬虫需要定义三个类成员
分别是
name
,start_requests()
,parse()

首先是name,给爬虫命名,命名的方式是在类里面直接对类属性name进行设置
name = 'name'
name 的官方文档的解释是

identifies the Spider. It must be unique within a project, that is, you can’t set the same name for different Spiders.

这是用来辨认爬虫的,在项目中必须是独一无二的,你不能和其他的爬虫取一个相同的名字。

如果没有给爬虫命名,爬虫会在初始化爬虫的时候抛出ValueError

    def __init__(self, name=None, **kwargs):
        if name is not None:
            self.name = name
        elif not getattr(self, 'name', None):
            raise ValueError("%s must have a name" % type(self).__name__)
        self.__dict__.update(kwargs)
        if not hasattr(self, 'start_urls'):
            self.start_urls = []

关于内置函数getattr

documentation:
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’)
is equivalent to x.foobar
. If the named attribute does not exist, default is returned if provided, otherwise AttributeError
is raised.

也就是说如果类有这个属性,我就返回这个属性对应的值,没有的话就返回默认值,这里的默认值是None

注意

Python 2 this must be ASCII only.
在Python2.X 版本中name的值必须是ASCII码

给爬虫命名后,接着需要对start_requests()进行设置

documentation:
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.

必须返回一个可迭代的大量请求(你可以返回一个含有大量请求的列表或者一个生成器)在爬虫开始爬取的时候。随后而来的请求将会被成功地从这些初始化的请求中生成。

也就是说必须类似于以这种形式返回

        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

道理都懂,那么scrapy.Request到底是什么呢,内容太多下一次单独讲好了

    原文作者:TimLee1996
    原文地址: https://www.jianshu.com/p/167dbee66897
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞