为所有 scrapy 蜘蛛编写函数

Write functions for all scrapy spiders

所以我正在尝试编写可以从所有 scrapy 蜘蛛调用的函数。 我的项目中有一个地方可以定义这些函数,还是需要在每个蜘蛛中导入它们?

谢谢

您不能在 python 中隐式导入代码(至少不能不进行修改),毕竟显式优于隐式 - 所以这不是一个好主意。

然而在 scrapy 中,基础 Spider class 具有通用的功能和方法是很常见的。

假设您有这棵树:

├── myproject
│   ├── __init__.py
│   ├── spiders
│   │   ├── __init__.py
│   │   ├── spider1.py
│   │   ├── spider2.py
├── scrapy.cfg

我们可以在 spiders/__init__.py 中创建一个基础蜘蛛:

class BaseSpider(Spider):
    def common_parse(self, response):
        # do something     

并在你的蜘蛛中继承它:

from myproject.spiders import BaseSpider
class Spider1(BaseSpider):
    def parse(self, response):
        # use common methods!
        if 'indicator' in response.body:
            self.common_parse(response)