Python 运行scrapy crawler的最简单方法,这样它就不会';不要阻止脚本

Python 运行scrapy crawler的最简单方法,这样它就不会';不要阻止脚本,python,scrapy,Python,Scrapy,提供从代码运行scrapy爬虫程序的多种方法: import scrapy from scrapy.crawler import CrawlerProcess class MySpider(scrapy.Spider): # Your spider definition ... process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' })

提供从代码运行
scrapy
爬虫程序的多种方法:

import scrapy
from scrapy.crawler import CrawlerProcess

class MySpider(scrapy.Spider):
    # Your spider definition
    ...

process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})

process.crawl(MySpider)
process.start() # the script will block here until the crawling is finished

但它们都会阻止脚本,直到爬网完成。python中以非阻塞、异步方式运行爬虫程序的最简单方法是什么?

我尝试了我能找到的所有解决方案,唯一适合我的方法是。但是为了使它能够与
scrapy 1.1rc1
配合使用,我不得不对它进行一些调整:

from scrapy.crawler import Crawler
from scrapy import signals
from scrapy.utils.project import get_project_settings
from twisted.internet import reactor
from billiard import Process

class CrawlerScript(Process):
    def __init__(self, spider):
        Process.__init__(self)
        settings = get_project_settings()
        self.crawler = Crawler(spider.__class__, settings)
        self.crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
        self.spider = spider

    def run(self):
        self.crawler.crawl(self.spider)
        reactor.run()

def crawl_async():
    spider = MySpider()
    crawler = CrawlerScript(spider)
    crawler.start()
    crawler.join()
因此,现在当我调用
crawl\u async
时,它开始爬网,并且不会阻塞当前线程。我是一个全新的
scrapy
,所以这可能不是一个很好的解决方案,但对我来说很有效

我使用了这些版本的库:

cffi==1.5.0
Scrapy==1.1rc1
Twisted==15.5.0
billiard==3.3.0.22

网民的回答是正确的
process.start()
调用
reactor.run()
,这会阻塞线程。只是我认为没有必要子类化
billiard.Process
。尽管没有很好的文档记录,
billiard.Process
确实有一组API来异步调用另一个函数,而无需子类化

from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

from billiard import Process

crawler = CrawlerProcess(get_project_settings())
process = Process(target=crawler.start, stop_after_crawl=False)


def crawl(*args, **kwargs):
    crawler.crawl(*args, **kwargs)
    process.start()

请注意,如果在crawl=False之后没有
stop\u,则在运行爬虫程序两次以上时,可能会遇到
ReactorNotRestartable
异常。

python yourscript.py&
我尝试使用您的解决方案,但得到:AttributeError:无法pickle本地对象“crawler.”。知道为什么吗?这里解释了原因