【问题标题】:Too many Selenium web driver instances when using with Scrapy与 Scrapy 一起使用时 Selenium Web 驱动程序实例过多
【发布时间】:2018-03-09 20:12:08
【问题描述】:

我正在使用 Scrapy 和 Selenium 创建一个网络爬虫。

代码如下所示:

class MySpider(scrapy.Spider):
  urls = [/* a very long list of url */] 

  def start_requests(self):
    for url in urls:
      yield scrapy.Request(url=url, callback=self.parse_item)

  def parse_item(self, response):
     item = Item()
     item['field1'] = response.xpath('some xpath').extract()[0]
     yield item

     sub_item_url = response.xpath('some another xpath').extract()[0]

     # Sub items are Javascript generated so it needs a web driver
     options = Options()
     options.add_argument('--headless')
     options.add_argument('--disable-gpu')

     driver = webdriver.Chrome(chrome_options=options)
     driver.set_window_size(1920, 1080)

     sub_item_generator = self.get_sub_item_generator(driver, sub_item_url)
     while True:
        try:
            yield next(sub_item_generator)
        except StopIteration:
            break

     driver.close()

  def get_sub_item_generator(driver, url):
     # Crawling using the web driver goes here which takes a long time to finish
     yield sub_item

问题是爬虫运行了一段时间,然后由于内存不足而崩溃。 Scrapy 不断地从列表中调度一个新的 URL,因此运行的 Web 驱动程序进程太多。

有什么方法可以控制 Scrapy 调度程序在运行一定数量的 Web 驱动程序进程时不调度新 URL?

【问题讨论】:

  • 考虑使用splash,比Selenium更轻量

标签: python selenium selenium-webdriver scrapy web-crawler


【解决方案1】:

您可以尝试将CONCURRENT_REQUESTS 设置为低于默认值16 (as shown here)

class MySpider(scrapy.Spider):
    # urls = [/* a very long list of url */]
    custom_settings = {
        'CONCURRENT_REQUESTS': 5  # default of 16 seemed like it was too much?
    }

【讨论】:

  • 尽管将“CONCURRENT_REQUESTS”设置为 1,但仍无法正常工作。正在创建更多 Chrome 进程,直到用完所有内存。
【解决方案2】:

尝试使用driver.quit() 而不是driver.close()

【讨论】:

  • 试过了,也没用。由于在到达此行之前内存不足,创建了太多 Chrome 进程并崩溃。
【解决方案3】:

尽管使用了driver.close(),但我也遇到了同样的问题,然后我这样做了,在脚本启动之前杀死所有 firefox 实例。

from subprocess import call
call(["killall", "firefox"])

【讨论】:

    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多