【问题标题】:Chrome with Selenium closes immediately after trying to start again after closing it with .quit()带有 Selenium 的 Chrome 在使用 .quit() 关闭后尝试重新启动后立即关闭
【发布时间】:2022-01-20 07:02:59
【问题描述】:

我的程序存在某种内存问题。过了一会儿,chrome 停止正常工作并显示一个页面,上面写着“Aw shucks. Ran out of memory”。我一直无法在 Python 中找到解决此问题的方法,因此作为一种迂回的解决方案,我设置了代码以关闭 webdriver 进程,然后重新启动它以清除内存并从中断处继续。

退出 webdriver 进程可以正常工作。但是,每当我尝试重新启动它时,它会打开一秒钟,然后关闭,我不知道为什么。代码如下:

from selenium import webdriver
driver = webdriver.Chrome()

#some code operations happen here that have nothing to do with the problem I'm having. It just navigates to different URLs.

if current_iteration >= 1500:
        print('Iteration greater than 1500. Restarting chrome driver...')
        driver.quit()
        current_iteration = 0
        time.sleep(5)
        print('Starting chrome process then waiting 20 seconds...')
        webdriver.Chrome()
        time.sleep(20)

程序到达这一点后,它只会说DevTools listening on ws://,后面跟着一堆数字。然后会弹出 chrome webdriver 窗口,然后在一秒钟后关闭。下一段代码是driver.get(),带有一个要导航到的 URL,但它退出时出现了一个很长的错误,我只能假设这是因为 chrome webdriver 窗口已关闭而不是打开。

webdriver 和 selenium 都是最新的。可能是什么问题?

【问题讨论】:

  • 你能发布你得到的回溯吗?此外,在我看来,driver.close() 可能是比driver.quit() 更好的方法
  • @AnandGautam driver.close() 的问题在于它不会关闭进程。添加driver.quit()的目的是为了修复chromedriver运行时间过长时面临的内存问题。

标签: python selenium google-chrome


【解决方案1】:

尝试将新驱动分配给循环中的driver变量:

from selenium import webdriver
driver = webdriver.Chrome()

#some code operations happen here that have nothing to do with the problem I'm having. It just navigates to different URLs.

if current_iteration >= 1500:
        print('Iteration greater than 1500. Restarting chrome driver...')
        driver.quit()
        current_iteration = 0
        time.sleep(5)
        print('Starting chrome process then waiting 20 seconds...')
        driver = webdriver.Chrome() # I've changed this line
        time.sleep(20)

【讨论】:

  • 这非常有效。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 2015-08-22
  • 2018-07-21
相关资源
最近更新 更多