Scrapy:如何从其他python脚本运行spider两次或更多

2024-07-04 13:51:47 发布

您现在位置:Python中文网/ 问答频道 /正文

废版本:1.0.5

我已经搜索了很长一段时间,但是大多数的解决方法在当前的版本中不起作用。在

我的蜘蛛是在京东定义的_蜘蛛网.py,运行spider的接口(按Scrapy Documentation学习)如下:

# interface
def search(keyword):
    configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'})
    runner = CrawlerRunner()
    d = runner.crawl(JingdongSpider,keyword)
    d.addBoth(lambda _: reactor.stop())
    reactor.run() # the script will block here until the crawling is finished

然后进来温度py我将调用上面的search(keyword)来运行spider。在

现在的问题是:我打过一次search(keyword),它成功了好吧。但是我打了两次电话

在温度py在

^{pr2}$

报告称:

Traceback (most recent call last): File "C:/Users/jiahao/Desktop/code/bbt_climb_plus/temp.py", line 7, in search('ipad2') File "C:\Users\jiahao\Desktop\code\bbt_climb_plus\bbt_climb_plus\spiders\jingdong_spider.py", line 194, in search reactor.run() # the script will block here until the crawling is finished File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 1193, in run self.startRunning(installSignalHandlers=installSignalHandlers) File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 1173, in startRunning ReactorBase.startRunning(self) File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 684, in startRunning raise error.ReactorNotRestartable() twisted.internet.error.ReactorNotRestartable

第一个搜索(关键字)成功了,但后者出错了。在

你能帮忙吗?在


Tags: theruninpysearchlinetwistedkeyword
2条回答

在代码示例中,调用扭曲电抗器在每次函数调用时启动它。这不起作用,因为每个进程只有一个反应器,而您不能start it twice。在

有两种解决问题的方法,都在documentation here中描述。要么坚持使用CrawlerRunner,但将reactor.run()移到search()函数之外,以确保它只被调用一次。或者使用CrawlerProcess并简单地调用crawler_process.start()。第二种方法更简单,您的代码如下所示:

from scrapy.crawler import CrawlerProcess
from dirbot.spiders.dmoz import DmozSpider

def search(runner, keyword):
    return runner.crawl(DmozSpider, keyword)

runner = CrawlerProcess()
search(runner, "alfa")
search(runner, "beta")
runner.start()

正如Pawel Miech所说

In your code sample you are making calls to twisted.reactor starting it on every function call. This is not working because there is only one reactor per process and you cannot start it twice.

我找到了解决问题的方法。只是使用多重处理。在

就像:

from multiprocessing import Process
def run_spider(keyword):
    if __name__ == '__main__':
        p = Process(target=jingdong_spider.search, args=(keyword.encode('utf-8'),))
        p.start()
        p.join()

如果每个人在使用python多处理时都有问题。最好看一下python文档。在

相关问题 更多 >

    热门问题