不关闭Python中Selenium浏览器的所有实例

问题描述 投票:0回答:1

我每天在 Python 中使用 Selenium 来抓取大量网页,发现它在 /tmp/ 中打开了 Edge 实例,最终填满了我的 Linux 驱动器空间。 /tmp/ 中留下的文件夹看起来像这样:-

/tmp/.com.microsoft.Edge.BX4XtO/

这是我正在使用的代码:-

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

def scrape_page(web_address):
   try:
      edge_options = webdriver.EdgeOptions()
      edge_options.use_chromium = True
      edge_options.add_argument('--remote-debugging-port=0')
      edge_options.add_argument('--no-first-run')
      edge_options.add_argument('--no-default-browser-check')
      edge_options.add_argument('--headless=new')
      edge_options.add_argument('--log-level=3')
      edge_options.add_argument("--disable-logging")
      edge_options.add_argument('--start-maximized') 
      edge_options.add_argument('--disable-infobars') 
      edge_options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
        
      # Creates 3x .com.microsoft.Edge. in /tmp/
      driver = webdriver.Edge(options = edge_options)

      driver.get(web_address)
      time.sleep(3)
      response = driver.find_element(By.XPATH, "/html/body").text
   except requests.exceptions.RequestException as e:  # This is the correct syntax
      print(e)
      logging.warning('Scraping {0} failed - {1}'.format(web_address, e))
      return
   finally:
      driver.close()
      driver.quit()
   return response

我发现当以下命令运行时:-

driver = webdriver.Edge(options = edge_options)

它在 /tmp/:-

中创建了三个 Edge 实例
.com.microsoft.Edge.bZsnHM/ .com.microsoft.Edge.tZLIcy/ .com.microsoft.Edge.wPEEWf/

在 quit() 命令之后,仅关闭两个实例,只剩下一个:-

.com.microsoft.Edge.bZsnHM/

这是最后一个例子

driver = webdriver.Edge(options = edge_options)

从三者中创造出来。我可以通过监视 /tmp/ 文件夹来确认这一点。

这提出了几个问题:-

首先,Selenium 应该打开 3 个实例吗?

其次,为什么 quit() 不关闭所有 Edge 实例?

第三,如何删除所有实例?

有关一些附加信息,当我使用 Chrome 而不是 Edge 时,会发生确切的情况。

感谢您的帮助和时间👍。

python-3.x selenium-webdriver
1个回答
0
投票

您可以使用 Firefox,并且每次执行此操作时都可以向空

/tmp
文件夹添加一些代码

import os
os.system("sudo rm -r /tmp/*")
© www.soinside.com 2019 - 2024. All rights reserved.