Chrome 浏览器在运行 selenium chrome webdriver 后关闭

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

我目前正在学习 Selenium 4.0,并设置了一个基本脚本,可以单击 Python 网站上的按钮。我正在使用 Chrome 网络驱动程序。但每当我运行代码时,就会打开一个 Chrome 窗口,显示 Python 网站,然后立即关闭。如何保持打开状态?

浏览器版本和网络驱动程序版本是相同的,我什至尝试过Edge网络驱动程序并重新安装Chrome。我什至尝试将网络驱动程序下载到本地目录,但这也不起作用。这是我当前的脚本:

from selenium import webdriver

from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

driver.get("https://www.python.org/")
print(driver.title)
submit = driver.find_element(By.ID, "submit")
submit.click()

运行后,我的终端给出以下消息:

====== WebDriver manager ======
Current google-chrome version is 101.0.4951
Get LATEST chromedriver version for 101.0.4951 google-chrome
Driver [/Users/user1/.wdm/drivers/chromedriver/mac64_m1/101.0.4951.41/chromedriver] found in cache
Welcome to Python.org

Process finished with exit code 0
python selenium selenium-webdriver
2个回答
5
投票

嗯,这是正确的行为,因为它会正确执行您告诉它的所有操作。事实上,您没有收到任何错误。执行代码后,Chrome 驱动程序被杀死,因为 Python 应用程序完成了执行

如果您希望驱动程序打开的浏览器保持打开状态,请使用 Chrome 选项并添加分离

from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

0
投票

@NicoCaldo 的解决方案对我不起作用。

我已经添加了

while True:
    pass

在我的脚本末尾,让 Chrome 保持打开状态。

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