selenium 网络驱动程序:如何切换到特定的窗口?

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

我遇到了许多在窗口之间切换的解决方案,其中之一是:

Set<String> allWindows = driver.getWindowHandles();
for(String currentWindow : allWindows){
   driver.switchTo().window(currentWindow);
}

但是,我不能去一个特定的窗口。谁能告诉我如何从父窗口切换到第三窗口(使用Java客户端库)?

oo7oh9g9

oo7oh9g91#

你就快到了。如果您想要切换到一个窗口,首先将窗口id存储在一个数组中,然后切换到某个特定的窗口。像下面这样的一些事情。如果你需要更多的帮助,请告诉我。编码快乐。

Set handles = driver.getWindowHandles();
        String[] individualHandle = new String[handles.size()];
        Iterator it = handles.iterator();
        int i =0;
        while(it.hasNext())
        {
            individualHandle[i] = (String) it.next();
            i++;
        }

driver.switchTo().window(individualHandle[1]);
eqfvzcg8

eqfvzcg82#

public static void switchWindow(String text) {
    WebDriver popup = null;
    Iterator<String> windowIterator = driver.getWindowHandles()
            .iterator();
    while (windowIterator.hasNext()) {
        String windowHandle = windowIterator.next();
        popup = driver.switchTo().window(windowHandle);
        String title = popup.getTitle();
        if (title.contains(text)) {
            break;
        }
    }
}

这将为您打开包含特定文本的任何窗口,您不必具体说明。

0g0grzrc

0g0grzrc3#

下面的方法将导航到特定窗口

public static void switchToParticularWindow(WebDriver driver, int index) throws InterruptedException {
        ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(index));
        Thread.sleep(2000);
        logger.info("Switched to new tab");
    }
ruarlubt

ruarlubt4#

公共类WindowHandles{

public static WebDriver driver;

public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
    driver.get("https://www.way2automation.com/lifetime-membership-club/");
    driver.manage().window().maximize();

    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

    driver.findElement(By.xpath("//*[@id=\"menu-item-25089\"]/a/span[2]")).click();
    driver.findElement(By.xpath("//*[@id=\"ast-desktop-header\"]/div[1]/div/div/div/div[2]/div/div/div/a[1]")).click();

    Set<String> window = driver.getWindowHandles();
    Iterator<String> it =window.iterator();

    while(it.hasNext())
    {
        String childWindow = it.next();
        String windowTitle = driver.switchTo().window(childWindow).getTitle();

         if(windowTitle.contains("Way2Automation"))
            {
                break;

            }       
    }

    System.out.println(driver.getTitle());

    driver.findElement(By.xpath("//*[@id=\"blueBarDOMInspector\"]/div/div/div/div[1]/a")).click();

    System.out.println(driver.getTitle());

}

}

相关问题