junit 脚本应等待浏览器手动关闭

kognpnkq  于 2022-11-11  发布在  其他
关注(0)|答案(4)|浏览(154)

我正在使用Java实现Selenium自动化,我有一个场景,只有在手动关闭当前场景的chrome浏览器时,我才需要移动到cubber功能文件中的下一个场景。

trnvg8h3

trnvg8h31#

你也可以这样做

WebDriver driver = new ChromeDriver();

    waitForDriverToClose(driver);

等待驱动程序关闭

private static void waitForDriverToClose(WebDriver driver) {
        try {
            WebDriverWait wait = new WebDriverWait(driver, 20);
            wait.until(ExpectedConditions.not(new ExpectedCondition<Boolean>() {
                @Override
                public Boolean apply(WebDriver driver) {
                    try {
                        driver.getTitle();
                        return true;
                    } catch (Exception ex) {
                        System.out.println("Couldn't Connect Driver / Driver Closed");
                        return false;
                    }
                }
            }));
        } catch (org.openqa.selenium.TimeoutException ex) {
            System.out.println("Timeout Trying Again");
            waitForDriverToClose(driver);
        }
    }
izj3ouym

izj3ouym2#

你可以尝试像循环,直到你得到浏览器死亡或无法到达异常。

WebDriver driver = new FirefoxDriver();

    driver.get("http://www.google.com");

    Boolean check = false;

    while (!check) {

        try {
            driver.getTitle();
            Thread.sleep(200);
        } catch (Exception e) {
            //you can verify correct exception here ie not reachable, dead etc..
            check = true;
        }

    }

    System.out.println("after browser close");
    //continue your code here
kcrjzv8t

kcrjzv8t3#

如果您在 selenium 检测运行时手动关闭浏览器,您将看到:org.openqa.selenium.NoSuchWindowException:找不到窗口。浏览器窗口可能已关闭。
您可以尝试捕获此异常,然后从那里开始。

bz4sfanl

bz4sfanl4#

from selenium import webdriver
mybrowser = webdriver.Chrome(executable_path='/chromedriver104.exe')
mybrowser.get("https://twitter.com/")
sleep(5)
check = False
while check !=True:
   try:
       mybrowser.title
       sleep(5)
   except:
       check = True

相关问题