我尝试在init函数中添加item_count = 0,然后在每个产项之前添加self.item_count += 1。
在此之后,我添加了if self.item_count == x time.sleep(y)。
但这似乎行不通。
我想增加这一点,因为我试图刮的网站有一个反刮政策,我不能通过150 000项。因此,我认为,暂停5-10分钟,每个50k的项目,将有助于我克服这个问题。
发布于 2022-01-31 03:06:45
可以使用from_crawler类方法将item_scraped信号连接到蜘蛛方法。然后在蜘蛛方法中,检查item_count是否可以被50000整除,然后使用crawler.engine.pause()方法暂停引擎所需的时间。然后使用crawler.engine.unpause()方法继续爬行。
在下面的示例代码中,我实现了每5项就暂停10秒作为示例。修改它,以适应您的需要(例如,每50000项5分钟)。
import scrapy
from scrapy import signals
import time
class SampleSpider(scrapy.Spider):
name = 'sample'
start_urls = ['http://quotes.toscrape.com/page/1/']
item_count = 0
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super(SampleSpider, cls).from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.item_scraped, signal=signals.item_scraped)
spider.crawler = crawler
return spider
def item_scraped(self, item):
# increase item count and then check if the item count is 5 from the previous pause
self.item_count += 1
if self.item_count % 5 == 0:
self.logger.info(f"Pausing scrape job...item count = {self.item_count}")
self.crawler.engine.pause()
time.sleep(10)
self.crawler.engine.unpause()
self.logger.info(f"Resuming crawl...")
def parse(self, response):
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').get(),
'author': quote.css('small.author::text').get(),
'tags': quote.css('div.tags a.tag::text').getall(),
}发布于 2022-10-19 18:37:00
相信我我什么都试过了。唯一起作用的是每页等待超过2分钟。由于我们有50页和1500项,我认为在这种情况下,我们应该使用其他工具。
https://stackoverflow.com/questions/70914132
复制相似问题