有没有一种方法可以首先在主窗口中搜索网络元素(如果找不到),然后开始在iframe中搜索?

时间:2019-04-05 13:47:24

标签: java selenium selenium-webdriver

要求:默认情况下,在主窗口中搜索网络元素,如果找到则执行操作,否则在iframe中搜索网络元素并执行所需的操作

硒3.141

'''
WebElement el = driver.findElement(By.xpath("//*[contains(text(),'here')]"));
    boolean displayFlag = el.isDisplayed();
    if(displayFlag == true)
    {
    sysout("element available in main window")  
    el.click();
    }
    else 
    {
      for(int f=0;f<10;f++)
      {
          sysout("element available in frameset")  
          switchToFrame(frameName[f]);
          el.click();
          System.out.println("Webelement not displayed");
      }
    }
'''

我的脚本本身在第一行失败。它试图在主窗口中查找元素,但该元素实际上在iframe中可用。

但是要求是首先在主窗口中搜索,然后才导航至iframe。如何处理这种用例?

有什么建议会有所帮助吗?谢谢。

1 个答案:

答案 0 :(得分:4)

是的,如果主窗口中不存在该元素,则可以编写一个循环遍历所有iframe。 Java实现:

git log <...> -- dir1/

Python实现

 if (driver.findElements(By.xpath("xpath goes here").size()==0){
     int size = driver.findElements(By.tagName("iframe")).size();
     for(int iFrameCounter=0; iFrameCounter<=size; iFrameCounter++){
        driver.switchTo().frame(iFrameCounter);
        if (driver.findElements(By.xpath("xpath goes here").size()>0){
            System.out.println("found the element in iframe:" + Integer.toString(iFrameCounter));
            // perform the actions on element here
        }
        driver.switchTo().defaultContent();
    }
 }