2

有没有办法在不进行任何硒切换的情况下获得窗口标题?

目前我正在使用以下代码:

public boolean switchToWindowByTitle(String title){
    String currentWindow = driver.getWindowHandle(); 
    Set<String> availableWindows = driver.getWindowHandles(); 
    if (!availableWindows.isEmpty()) { 
         for (String windowId : availableWindows) {
              String switchedWindowTitle=driver.switchTo().window(windowId).getTitle();
              if ((switchedWindowTitle.equals(title))||(switchedWindowTitle.contains(title))){ 
                  return true; 
              } else { 
                driver.switchTo().window(currentWindow); 
              } 
          } 
     } 
     return false;
}
4

3 回答 3

0

页面标题是标签,出现在浏览<title>器窗口的顶部,它是.<header><html>

所以Selenium驱动的WebDriver需要关注特定的Browsing Context来提取Page Title

其中Window Handle是一个唯一标识符,它保存了所有窗口的地址,并且可以返回字符串值。所有的浏览器都会有一个独特的窗口句柄。此getWindowHandles()功能有助于检索所有窗口的句柄。

所以Selenium驱动的WebDriver可以从浏览上下文中收集窗口句柄,即使没有单独关注它们。


结论

因此,如果不切换到特定的Window / TAB ,就不可能获得窗口 / 选项卡的标题。

于 2021-11-14T13:22:56.143 回答
-3

本准则将达到目的。调用该函数如下 swithToWindow("window Name");

public static Boolean switchToWindow(String title) {
    String Parent_window = driver.getWindowHandle();
    Set<String> handles = driver.getWindowHandles();
    for(String handle : handles) {
        driver.switchTo().window(handle);
        if (driver.getTitle().equalsIgnoreCase(title)) {
            return true;
        }
    }
    driver.switchTo().window(Parent_window);
    return false;
}
于 2018-07-11T09:43:41.957 回答
-3
        ArrayList<String> tabs = new ArrayList<String> driver.getWindowHandles());
            driver.switchTo().window(tabs.get(1));

            String parentWindow=driver.getWindowHandle();

               Set<String> windows= driver.getWindowHandles();
               for(String child:windows){
                   try{
                   if(!child.equalsIgnoreCase(parentWindow)){
                          driver.switchTo().window(child);
                          String windowTitle=driver.getTitle();
                          if(windowTitle.equals("book My Show")){
                              System.out.println("Window found");

                          }
                          else{
                              System.out.println("no windows found");
                          }

                   }
                   }catch(Exception e){
                       e.printStackTrace();
                       System.out.println("");
                   }
               }
               driver.switchTo().window(parentWindow);

} }

于 2019-05-08T10:39:02.177 回答