让这段代码从脚本(http://doc.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script)运行scrapy crawler。但它不起作用。
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log,signals
from spiders.egov import EgovSpider
from scrapy.utils.project import get_project_settings
def run():
spider =EgovSpider()
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configured
crawler.crawl(spider)
crawler.start()
log.start()
reactor.run()
from apscheduler.schedulers.twisted import TwistedScheduler
sched = TwistedScheduler()
sched.add_job(run, 'interval', seconds=10)
sched.start()
我的蜘蛛:
import scrapy
class EgovSpider(scrapy.Spider):
name = 'egov'
start_urls = ['http://egov-buryatia.ru/index.php?id=1493']
def parse(self, response):
data = response.xpath("//div[@id='main_wrapper_content_news']//tr//text()").extract()
print data
print response.url
f = open("vac.txt","a")
for d in data:
f.write(d.encode(encoding="UTF-8") + "\n")
f.write(str(now))
f.close()
如果我替换“reactor.run()”行,10秒后蜘蛛已启动一次:
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log,signals
from spiders.egov import EgovSpider
from scrapy.utils.project import get_project_settings
def run():
spider =EgovSpider()
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configured
crawler.crawl(spider)
crawler.start()
log.start()
from apscheduler.schedulers.twisted import TwistedScheduler
sched = TwistedScheduler()
sched.add_job(run, 'interval', seconds=10)
sched.start()
reactor.run()
我对python和英语经验不足:)请帮助我。
答案 0 :(得分:1)
我今天遇到了同样的问题。这是一些信息。
扭曲的反应堆一旦运行并停止就无法重启。您应该启动一个长期运行的反应堆并定期添加爬虫任务。
为了进一步简单编码,您可以使用CrawlerProcess.start(),其中包括reactor.run()。
from scrapy.crawler import CrawlerProcess
from spiders.egov import EgovSpider
from scrapy.utils.project import get_project_settings
from apscheduler.schedulers.twisted import TwistedScheduler
process = CrawlerProcess(get_project_settings())
sched = TwistedScheduler()
sched.add_job(process.crawl, 'interval', args=[EgovSpider], seconds=10)
sched.start()
process.start(False) # Do not stop reactor after spider closes