简体   繁体   English

如何阻止 scrapy 两次运行同一个蜘蛛?

[英]How to stop scrapy from running the same spider twice?

So I'm following the doc for running the spider within the code, but for some reason after it finishes crawling, the spider is run again.所以我正在关注在代码中运行蜘蛛的文档,但由于某种原因,在它完成爬行后,蜘蛛再次运行。 I've tried adding the stop_after_crawl and stop() functions but to no luck.我尝试添加 stop_after_crawl 和 stop() 函数,但没有成功。 It also gives me the error below after it attempting to run a second time.在尝试第二次运行后,它也给了我下面的错误。

twisted.internet.error.ReactorNotRestartable twisted.internet.error.ReactorNotRestartable

Any help is appreciated, thanks!任何帮助表示赞赏,谢谢!

The Code编码

class DocSpider(scrapy.Spider):
"""
This is the broad scraper, the name is doc_spider and can be invoked by making an object
of the CrawlerProcess() then calling the class of the Spider. It scrapes websites csv file
for the content and returns the results as a .json file.
"""

#Name of Spider
name = 'doc_spider'

#File of the URL list here
urlsList = pd.read_csv('B:\docubot\DocuBots\Model\Data\linksToScrape.csv')
urls = []
#Take the urls and insert them into a url list
for url in urlsList['urls']:
    urls.append(url)

#Scrape through all the websites in the urls list
start_urls = urls

#This method will parse the results and will be called automatically
def parse(self, response):
    data = {}
    #Iterates through all <p> tags
    for content in response.xpath('/html//body//div[@class]//div[@class]//p'):
        if content:
            #Append the current url
            data['links'] = response.request.url
            #Append the texts within the <p> tags
            data['texts'] = " ".join(content.xpath('//p/text()').extract())

    yield data

def run_crawler(self):
    settings = get_project_settings()
    settings.set('FEED_FORMAT', 'json')
    settings.set('FEED_URI', 'scrape_results.json')
    c = CrawlerProcess(settings)
    c.crawl(DocSpider)
    c.start(stop_after_crawl=True)

D = DocSpider()
D.run_crawler()

Error Terminal Output错误端子 Output

Traceback (most recent call last):
File "web_scraper.py", line 52, in <module>
D.run_crawler()
File "web_scraper.py", line 48, in run_crawler
c.start(stop_after_crawl=True)
File "B:\Python\lib\site-packages\scrapy\crawler.py", line 312, in start
reactor.run(installSignalHandlers=False)  # blocking call
File "B:\Python\lib\site-packages\twisted\internet\base.py", line 1282, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "B:\Python\lib\site-packages\twisted\internet\base.py", line 1262, in startRunning
ReactorBase.startRunning(self)
File "B:\Python\lib\site-packages\twisted\internet\base.py", line 765, in startRunning
raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable

You need to move run_spider outside of DocSpider class:您需要将 run_spider 移到run_spider DocSpider

class DocSpider(scrapy.Spider):
    .....

def run_crawler(self):
    settings = get_project_settings()
    settings.set('FEED_FORMAT', 'json')
    settings.set('FEED_URI', 'scrape_results.json')
    c = CrawlerProcess(settings)
    c.crawl(DocSpider)
    c.start(stop_after_crawl=True)


run_crawler()

SOLUTION解决方案

Found the solution, apparently every time I imported the code, scrapy would run the spider again.找到了解决方案,显然每次我导入代码时,scrapy 都会再次运行蜘蛛。 So I had to specify to only run the spider only when I run the code by adding an if statement.因此,我必须通过添加 if 语句指定仅在运行代码时才运行蜘蛛。

    def run_crawler(self):
       if __name__ ==  "__main__":
           settings = get_project_settings()
           settings.set('FEED_FORMAT', 'json')
           settings.set('FEED_URI', 'scrape_results.json')
           c = CrawlerProcess(settings)
           c.crawl(DocSpider)
           c.start(stop_after_crawl=True)

newProc = DocSpider()
newProc.run_crawler()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM