在我的 Python 脚本中执行了以下代码行:
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
此行可能会失败或成功,具体取决于明显的随机条件(这是由于正在加载的扩展,但这与此处无关)。
问题是,即使这一行失败,并引发 WebDriverException
,Chromium 实例仍会生成,最终会淹没我的整个桌面,因为我在 while 循环中运行这一行,直到它有效。
以下代码块不起作用,因为未定义驱动程序。
try:
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
except WebDriverException:
driver.quit()
如何巧妙地做到这一点?
最佳答案
正如您提到的,您有以下行:
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
并且这一行可能失败
或成功
。所以有 2 个用例可以按如下方式解决:
Success
:如果上面提到的代码行是Success
,我们将使用driver.quit()
直接如下:try: driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options) #other code driver.quit()
Failure
:如果上面提到的代码行是Failure
,我们将使用 taskkill来自 os 的命令强制终止chromedriver
process
的模块如下:import os #other code try: driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options) #other code driver.quit() except WebDriverException: os.system("taskkill /im chromedriver.exe")
琐事
通过命令 webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
无论 Chromium
session 是否产生,一个单独的 chromedriver
session 将始终产生,我们在代码中已经注意了这一点。如果您还想终止 Chromium
session ,则还必须添加以下行:
os.system("taskkill /im chrome.exe")
关于Python Selenium - 如何终止未成功生成的 Chromedriver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48118496/