How to switch to a new window using Selenium?

前端 未结 1 1194
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 00:13

In my code i have reached to a page using selenium in whihc there is a link which opens as a popup on the same page, but that link is using , so it is like a new page which is o

1条回答
  •  失恋的感觉
    2021-01-29 00:45

    After clicking the link you need to wait until Selenium realizes there are now totally 2 windows.

    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 numberOfWindowsToBe(final int numberOfWindows) {
        return new ExpectedCondition() {
          @Override
          public Boolean apply(WebDriver driver) {
                    driver.getWindowHandles();
            return driver.getWindowHandles().size() == numberOfWindows;
          }
        };
    }
    

    All i want is to get the driver of the popup page only

    EDIT: The driver for the master window is the driver for the popup as popup itself is the part of the master window. The only exception is, if the popup is present in a frame, then you need to switch to the frame then you can perform actions on the elements present in the popup.

    EDIT: If I understand you correctly, you want to get the page source of the popup. As popup is part of the master window. What I would do is

    popup.getAttribute("innerHTML"); Where popup is of type WebElement.

    For example if HTML of the master window is like

     
    
    .....
    
    
    ...
    ...
    ..
    
    ...
    ..
    
    
    

    then

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

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

    will solve the problem.

    0 讨论(0)
提交回复
热议问题