硒脚本在python上完成后如何保持chrome浏览器窗口打开以重新使用

问题描述

在 selenium 执行完我的测试脚本后,我试图让 chrome 浏览器保持打开状态.我想重复使用同一个窗口来运行我的第二个脚本.

I am trying to keep the chrome browser open after selenium finishes executing my test script. I want to re-use the same window for my second script to run.


解决方案

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

Browser window closes when your Chrome webdriver instance variable is garbage collected. If you want to avoid this even when your script finishes executing, you can make it global. I.e.:

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

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

Explanation: A selenium.webdriver.Chrome class instance contains an instance of a Service class. The latter has a __del__ method which is called when the instance is being destructed during garbage collection process. The method in turn stops the service and causes Chrome browser window to close.

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

This also explains why some users don't observe this behavior. I suspect that this is because they have Chrome webdriver instance variable at file scope, not inside a function.

相关文章