Selenium WebDriver在切换之前获取当前帧

Tha*_*han 4 java selenium selenium-webdriver

通过切换某个iFrame,我有一个自定义操作来查找元素.它使用以下本机操作: driver.switchTo().frame(requested_frame) 目前我在切换到确切的iframe之前每次切换回默认内容.

现在我需要通过以下scnario来提高它的性能:

  • 检查当前内容/框架
  • 如果requested_frame=currentFrame那么不需要切换
  • 如果requested_frame=null然后切换到默认值(如果currentFrame=default那么再次无需切换)
  • 如果requested_frame!=null && requested_frame!=currentFrame然后切换到默认值,并切换到requested_frame帧.

所以我现在需要的是获得当前帧.有什么方法可以得到它吗?

Tha*_*han 8

作为我自己的问题"Selenium WebDriver得到当前帧"的确切答案,我找到了以下方法来做到这一点.

JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
String currentFrame = jsExecutor.executeScript("return self.name");
Run Code Online (Sandbox Code Playgroud)

但是在这里,JavascriptExecutor每次都执行命令以获取当前帧.所以如果我考虑一下表演,我想选择#Saurabh Gaur的答案作为最佳答案.我希望我的回答对别人有帮助:-)


稍后添加

我刚刚用我的当前版本进行了一个小测试,使用全局变量和js命令帮助.

[ 在2个嵌套iframe中的4个不同元素中执行动作的时间(ms)1000次.(共找到4000个元素动作) ]

|          | Switch everytime | Global variable | JS command | 
|----------|------------------|-----------------|------------| 
|          | 2023             | 1950            | 2911       | 
|          | 1902             | 2091            | 2992       | 
|          | 2014             | 1974            | 3020       | 
|          | 1934             | 1931            | 3097       | 
|          | 1997             | 1965            | 3180       | 
|----------|------------------|-----------------|------------|
| Average  | 1974             | 1982.2          | 3040       | 
Run Code Online (Sandbox Code Playgroud)

因此,我每次"切换默认值"的当前性能都不差:D

  • JavascriptExecutor jsExecutor = (JavascriptExecutor) 驱动程序; Stringframe = (String) jsExecutor.executeScript("返回 self.location.toString()"); (2认同)

Sau*_*aur 5

您需要实施以下方法:-

String frame = 'your frame';
String currentFrame = null;
// make this currentFrame as global

if ((null != frame) && (!"".equals(frame))) {
        if (!frame.equals(currentFrame)) {
            switchToFrame(frame);
            currentFrame = frame;
        }
    } else {
        currentFrame = "";
        webDriver.switchTo().defaultContent();
    }

public void switchToFrame(String frame) {
    webDriver.switchTo().defaultContent();
    webDriver.switchTo().frame(frame);
}
Run Code Online (Sandbox Code Playgroud)

希望它能满足您的所有条件..:)