首先值得注意的是,通常只有 一个
Twisted反应堆正在运行,并且它不可重启(如您所发现)。第二个是应该避免阻塞任务/功能(即
time.sleep(n)),并应使用异步替代方法(例如’reactor.task.deferLater(n,…)`)代替。
要从Twisted项目中有效使用Scrapy,需要使用
scrapy.crawler.CrawlerRunner核心API,而不是
scrapy.crawler.CrawlerProcess。两者之间的主要区别是为您
CrawlerProcess运行Twisted的操作
reactor(因此很难重新启动反应堆),而后者
CrawlerRunner依赖于开发人员来启动反应堆。这是您的代码使用以下代码的样子
CrawlerRunner:
from twisted.internet import reactorfrom quotesbot.spiders.quotes import QuotesSpiderfrom scrapy.crawler import CrawlerRunnerdef run_crawl(): """ Run a spider within Twisted. once it completes, wait 5 seconds and run another spider. """ runner = CrawlerRunner({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', }) deferred = runner.crawl(QuotesSpider) # you can use reactor.callLater or task.deferLater to schedule a function deferred.addCallback(reactor.callLater, 5, run_crawl) return deferredrun_crawl()reactor.run() # you have to run the reactor yourself


