How to switch to a new window using Selenium?

In my code, I reached the page using selenium, which has a link that opens as a popup on the same page, but this link is used, so it looks like a new page that opens in a new window.

I can click on this link and open the page, but when I do driver.getWindowHandles (), it returns a size of only 1, not 2, which is why I cannot switch to a new window.

The following is the code I'm using:

    String parent = driver.getWindowHandle();
    driver.findElement(By.xpath("//a[@id='abc']")).click();
    // after clicking on the link
    try{
    Thread.sleep(1000);

    Set<String> availableWindows = driver.getWindowHandles();//this set size is
   // returned as 1 and not 2
    String newWindow = null;
    for (String window : availableWindows) {
        if (!parent.equals(window)) {
            newWindow = window;
        }
    }
    assertNotNull(newWindow);

    // switch to new window
    driver.switchTo().window(newWindow);
    // do assert the elements in the new window
    // and then close the new window
    driver.close();
    // switch to parent
    driver.switchTo().window(parent);
    // close main window
    driver.close();}
    catch(Exception e){

Since the popup is part of the main window itself, that is why I cannot get the correct size by doing getWindowHandle ();

, . , , .

, , ?

, . , ,

0
1

, Selenium , 2 .

String parent = driver.getWindowHandle();
    driver.findElement(By.xpath("//a[@id='alertHistoryLink']")).click();
    // after clicking on the link
    // call the method numberOfWindowsToBe as follows
    WebDriverWait wait = new WebDriverWait(driver, 15, 100);
    wait.until(numberOfWindowsToBe(2));

public static ExpectedCondition<Boolean> numberOfWindowsToBe(final int numberOfWindows) {
    return new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driver) {
                driver.getWindowHandles();
        return driver.getWindowHandles().size() == numberOfWindows;
      }
    };
}

, ,

EDIT: , . - , , , .

EDIT: , . .

popup.getAttribute( "innerHTML" ); popup WebElement.

, HTML

 <html>
<head>
.....
</head>
<body>
...
...
..
<div id = popup> 
//html elements present in popup
</div>
...
..
</head>
</html>

WebElement popup = driver.findElement(By.xpath("//div[@id='popup']"));

String htmlInsidePopup = popup.getAttribute("innerHTML");
System.out.println(htmlInsidePopup);

.

0

All Articles