java - 使用Selenium和java识别页面中的iframe数量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31532534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:12:50  来源:igfitidea点击:

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

javaseleniumiframeselenium-webdriverframe

提问by justcurious

Is there any method to identify the following in Selenium?

是否有任何方法可以识别 Selenium 中的以下内容?

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

采纳答案by TEH EMPRAH

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

For acquiring details of current frame I propose you switch to it using a WebElementobject and switchTo, and then get attributes like you normally do, with getAttribute

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

UPD

UPD

In fact, yes, first will give the amount of iframes in current context. If you don't want to do it recursively, but want a quick and working (dirty) solution - just get the page source and find all inclusions of "<iframe"string

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

回答by drkthng

Here an example how you can approach it:

这是一个如何处理它的示例:

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

回答by Tom Trumper

As the other answers have stated, you can identify the number of frames in the currently focused contextusing:

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

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

However this will not identify any frames that are children of another frame. To do so, you will need to switch to that parent frame first.

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

To retrieve attributes such as name or id for the currently focused frame you can use JavascriptExecutor like so:

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

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