私はこのガイドに従っていますhttp://doc.scrapy.org/en/0.16/topics/practices.html#スクリプトからscrapyを実行する私のスクリプトから scrapy を実行します。以下は私のスクリプトの一部です:
crawler = Crawler(Settings(settings))
crawler.configure()
spider = crawler.spiders.create(spider_name)
crawler.crawl(spider)
crawler.start()
log.start()
reactor.run()
print "It can't be printed out!"
期待通りに動作します。ページにアクセスし、必要な情報をスクレイピングし、出力 json を指示された場所 (FEED_URI 経由) に保存します。ただし、スパイダーが作業を終了すると (出力 json の番号で確認できます)、スクリプトの実行が再開されません。おそらく、これは scrapy の問題ではありません。答えは、twisted のリアクターのどこかにあるはずです。スレッドの実行を解放するにはどうすればよいですか?
ベストアンサー1
スパイダーが終了したら、リアクターを停止する必要があります。これは、spider_closed
信号を聞くことで実行できます。
from twisted.internet import reactor
from scrapy import log, signals
from scrapy.crawler import Crawler
from scrapy.settings import Settings
from scrapy.xlib.pydispatch import dispatcher
from testspiders.spiders.followall import FollowAllSpider
def stop_reactor():
reactor.stop()
dispatcher.connect(stop_reactor, signal=signals.spider_closed)
spider = FollowAllSpider(domain='scrapinghub.com')
crawler = Crawler(Settings())
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start()
log.msg('Running reactor...')
reactor.run() # the script will block here until the spider is closed
log.msg('Reactor stopped.')
コマンドラインのログ出力は次のようになります。
stav@maia:/srv/scrapy/testspiders$ ./api
2013-02-10 14:49:38-0600 [scrapy] INFO: Running reactor...
2013-02-10 14:49:47-0600 [followall] INFO: Closing spider (finished)
2013-02-10 14:49:47-0600 [followall] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 23934,...}
2013-02-10 14:49:47-0600 [followall] INFO: Spider closed (finished)
2013-02-10 14:49:47-0600 [scrapy] INFO: Reactor stopped.
stav@maia:/srv/scrapy/testspiders$