driver = webdriver.Chrome 在用户执行代码之前打开浏览器

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

我有一个 GUI 应用程序,无需打开浏览器即可打开。仅当用户单击按钮后,浏览器才应打开。

driver = webdriver.Chrome()
是多个类使用的全局设置。这是应用程序打开时启动的代码:

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

# The browser has opened before the code gets executed.

提前感谢您的帮助。

更新:经过更多思考后,我认为解决方案是在 GUI 按钮调用的函数中实例化“驱动程序”,然后将驱动程序传递给其他函数。因此,它不是使驱动程序成为全局的,而是根据需要传递的局部变量。我需要时间尝试一下。

python selenium-webdriver webdriver
1个回答
0
投票

为了防止此代码在其预定时间之前运行,您可以使用一个函数。例如

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def open_browser():
    chrome_options = Options()
    chrome_options.add_experimental_option("detach", True)
    driver = webdriver.Chrome(options=chrome_options)
    return driver

然后,每当您想打开 chrome 浏览器时,您都需要调用此函数。然后它会返回驱动程序,您可以像平常一样使用它。 这是创建驱动程序后使用该驱动程序的示例。

driver = open_browser()
    driver.get('https://example.com')

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