如何在Python中从普通类调用spider类?

时间:2018-06-17 18:37:53

标签: python scrapy web-crawler scrapy-spider

我有以下问题:

我想在另一个类中调用一个蜘蛛,比如Ruby on Rails中的Jobs。例如:

class Foo:
  MySpider()

然后,调用Foo()来执行我的蜘蛛。我不知道我的观点是否足够明确,但我会感激任何帮助:)

1 个答案:

答案 0 :(得分:0)

您可以通过多种方式完成此操作(即使使用函数式编程),但我只想向您展示一些:

<强> 1。构造

你可以在MySpider的构造函数中实例化(我认为你的意思是“call”)Foo

class MySpider(object):

    def __init__(self):
        super().__init__()
        print('In MySpider __init__.')


class Foo(object):

    def __init__(self):
        super().__init__()
        print('In Foo __init__.')
        MySpider()


Foo()

'''
prints:

In Foo __init__.
In MySpider __init__.
'''

但请注意,需要创建Foo的新实例才能实例化并保留对MySpider的引用。如果您需要保留引用,只需将self.my_spider = MySpider()放入__init__

<强> 2。添加__call __

__init__方法外,您还可以添加__call__方法。这基本上做的是允许直接调用实例化对象。如果您拥有return self,则允许调用链发生:

class Foo(object):

    def __call__(self, *args, **kwargs):
        print('In Foo __call__.')
        MySpider()
        return self


Foo()()()

'''
prints:

In Foo __init__.
In MySpider __init__.
In Foo __call__.
In MySpider __init__.
'''