使用带有 java 的 Selenium 识别页面中的 iframe 数量?

Identifying number of iframes in a page using Selenium with java?

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

Number of iframes in a page
Attributes/Details of the current iframe
driver.findElements(By.xpath("//iframe")).size();

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

UPD

其实是的,首先会给出当前上下文中iframe的数量。如果你不想递归地做,但想要一个快速有效的(脏)解决方案 - 只需获取页面源并找到 "<iframe" string

的所有包含

这里有一个如何处理它的例子:

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());
        }

如其他答案所述,您可以使用以下方法识别当前聚焦上下文中的帧数

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

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

要检索当前聚焦框架的名称或 ID 等属性,您可以像这样使用 JavascriptExecutor:

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