Selenium 有没有办法阻止 ctrl+c 关闭浏览器窗口

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

在我的程序中我得到了这样的东西:

driver = webdriver.Chrome(options=Options()) #calling the driver
driver.get(website) #opening the website
try:
    while True:
        do_something() #Here I do a couple of things
except KeyboardInterrupt: 
    #When I'm done with the while loop above(the goal is to be able to stop at any point of the loop) I use ctrl+c
    pass
#Here the program continues but selenium closes the window even though I didn't call for driver.quit().

虽然它成功停止了 while 循环并且没有结束程序本身,但 selenium 会关闭窗口浏览器。有没有办法阻止selenium关闭窗口?

python selenium selenium-webdriver try-catch keyboardinterrupt
2个回答
2
投票

当您完成 while 循环而不是使用 ctrl + C 时,您可以轻松地进行如下操作:

from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException

driver = webdriver.Chrome(options=Options()) #calling the driver
driver.get(website) #opening the website
while True:
    try:
        do_something() #Here I do a couple of things
    except (NoSuchElementException, WebDriverException, TimeoutException):
        break
# Here the program continues and selenium doesn't closes the window even

0
投票

当 Chrome 进程与其父进程在同一进程组中创建时,Chrome 也会收到 SIGINT。 为了防止这种行为,Chrome 需要在单独的进程组中生成。

请参阅 ryyyn 的答案 如何让 CTRL+C 中断脚本而不关闭 Selenium WebDriver?.

发布这个答案,因为我缺乏评论/标记为重复的点。

© www.soinside.com 2019 - 2024. All rights reserved.