我开始学习如何在Java中使用Selenium处理浏览器中的多个选项卡。看起来我下面的代码无法正常工作。

    import java.util.ArrayList;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class HandlingWindows {

    public static void main(String[] args) throws InterruptedException
    {

        WebDriver driver= new FirefoxDriver();
        driver.get("https://www.facebook.com/");
        String parent= driver.getWindowHandle();
        System.out.println("Parent Window is"+parent);

        //Get Data Policy
        WebElement we= driver.findElement(By.linkText("Data Policy"));
        //Click Data Policy link
        we.click();
        //Create an arrayList
        ArrayList<String> s1= new ArrayList<String>(driver.getWindowHandles());


         for(String s2:s1)
           {


            if(!(s2.equalsIgnoreCase(parent)))
              {
               driver.switchTo().window(s2);
               Thread.sleep(5000);
               System.out.println(driver.getWindowHandle());
               System.out.println("get title of window"+driver.getTitle());
              }
             }
    }

}


请让我知道如何在不使用标题的情况下显示“数据策略”标题
getWindowHandles()。

最佳答案

getWindowHandles()可以正常工作,但是在调用getWindowHandles()之前,您必须按照以下步骤诱使WebDriverwait:

System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent= driver.getWindowHandle();
System.out.println("Parent Window is"+parent);
driver.findElement(By.linkText("Data Policy")).click();
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> s1= driver.getWindowHandles();
for(String s2:s1)
{
    if(!parent.equalsIgnoreCase(s2))
        {
            driver.switchTo().window(s2);
            Thread.sleep(5000);
            System.out.println(driver.getWindowHandle());
            System.out.println("get title of window"+driver.getTitle());
        }
}


控制台输出:

Parent Window is4294967297
4294967303
get title of windowData Policy

关于java - getWindowHandles()在Firefox 58中不起作用。焦点停留在父选项卡上,并且不会转移到下一个选项卡,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49142180/

10-12 22:06