【问题标题】:Identifying number of iframes in a page using Selenium with java?使用 Selenium 和 java 识别页面中的 iframe 数量?
【发布时间】:2015-10-10 12:32:11
【问题描述】:

Selenium 中有什么方法可以识别以下内容吗?

Number of iframes in a page
Attributes/Details of the current iframe

【问题讨论】:

  • 谢谢大家!连同 size() 方法,使用 switchTo() 方法导航到框架。最初我很难使用 java 代码识别当前帧(我想知道是否有一个!)。通过在 chrome 中检查元素的帮助,确定了框架名称,现在我能够识别该框架中的元素。

标签: java selenium iframe selenium-webdriver frame


【解决方案1】:
driver.findElements(By.xpath("//iframe")).size();

为了获取当前帧的详细信息,我建议您使用WebElement 对象和switchTo 切换到它,然后像平常一样使用getAttribute 获取属性

UPD

事实上,是的,首先会给出当前上下文中 iframe 的数量。如果您不想递归地执行此操作,但想要一个快速且有效(肮脏)的解决方案 - 只需获取页面源并找到 "<iframe" 字符串的所有包含项

【讨论】:

    【解决方案2】:

    正如其他答案所述,您可以在当前关注的上下文中识别帧数:

    driver.findElements(By.xpath("//iframe")).size();
    

    但是,这不会识别任何属于另一个框架的子框架的框架。为此,您需要先切换到该父框架。

    要检索当前焦点框架的名称或 id 等属性,您可以使用 JavascriptExecutor,如下所示:

    String currentFrameName = (String)((JavascriptExecutor) driver).executeScript("return window.frameElement.name");
    

    【讨论】:

    • 这是我认为最好的答案。
    • 我在使用上面的代码时收到以下错误:“无法读取 null 的属性 'name'”我这里有什么遗漏吗?
    • 当您尝试执行“return window.frameElement.name”时,您是否处于页面的顶层上下文?如果您关注页面的顶级内容,“window.frameElement”将返回 null。
    【解决方案3】:

    这里有一个示例:

    WebDriver driver = new FirefoxDriver();
    driver.get("http://the-internet.herokuapp.com/iframe");
    
    // find all your iframes
    List<WebElement> iframes = driver.findElements(By.xpath("//iframe"));
            // print your number of frames
            System.out.println(iframes.size());
    
            // you can reach each frame on your site
            for (WebElement iframe : iframes) {
    
                // switch to every frame
                driver.switchTo().frame(iframe);
    
                // now within the frame you can navigate like you are used to
                System.out.println(driver.findElement(By.id("tinymce")).getText());
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2013-07-22
      相关资源
      最近更新 更多