如何保持Chrome浏览器窗口打开,以便在python上完成selenium脚本后重复使用[复制]

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

这个问题在这里已有答案:

我想在selenium完成执行我的测试脚本后保持Chrome浏览器打开。我想重新使用相同的窗口来运行我的第二个脚本。

python selenium webdriver selenium-chromedriver ui-automation
3个回答
1
投票

当您的Chrome webdriver实例变量被垃圾回收时,浏览器窗口将关闭。如果要在脚本完成执行时避免这种情况,可以将其设置为全局。即:

def test():
    global driver # this will prevent the driver variable from being garbage collected
    driver = webdriver.Chrome()
    ...

Explanation:selenium.webdriver.Chrome类实例包含Service类的实例。后者有一个__del__方法,在垃圾收集过程中实例被破坏时调用。该方法依次停止服务并导致Chrome浏览器窗口关闭。

这也解释了为什么有些用户没有观察到这种行为。我怀疑这是因为他们在文件范围内有Chrome webdriver实例变量,而不是函数内部。


0
投票

这应该就像在测试用例结束时不调用driver.quit()一样简单。您应该将Chrome窗口置于打开状态。


0
投票

我知道在WATIR(Ruby语言)中要做什么,我正在编写下面的代码,所以它可能会让你知道如何处理你的语言

require 'watir'
caps = Selenium::WebDriver::Remote::Capabilities.chrome(chrome_options: {detach: true})
b = Watir::Browser.new :chrome, desired_capabilities: caps
b.goto('www.google.co.uk')

下面给出的这一行很重要,如果你可以用你的语言(python)重新写这行,那么你可能会阻止关闭chrome浏览器

caps = Selenium::WebDriver::Remote::Capabilities.chrome(chrome_options: {detach: true})
© www.soinside.com 2019 - 2024. All rights reserved.