• Selenium,定位 iframe 中元素


    有时候我们在定位一个页面元素的时候发现一直定位不了, 反复检查自己写的定位器没有任何问题,代码也没有任何问题。这时你就要看一下这个页面元素是否在一个 iframe 中,这可能就是找不到的原因之一。如果你在一个 defaultcontent 中查找一个在 iframe 中的元素,那肯定是找不到的。反之你在一个iframe 中查找另一个 iframe 元素或 default content 中的元素,那必然也定位不到。
    selenium webdriver 中提供了进入一个 iframe 的方法:
    WebDriver org.openqa.selenium.WebDriver.TargetLocator.frame(String nameOrId)
    也提供了一个返回 default content 的方法:
    WebDriver org.openqa.selenium.WebDriver.TargetLocator.defaultContent()
    这样使我们面对 iframe 时可以轻松应对。
    以下面的 html 代码为例,我们看一下处理 iframe。
     1 main.html
     2 Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)
     3 <html>
     4 <head>
     5 <title>FrameTest</title>
     6 </head>
     7 <body>
     8 <div id = "id1">this is a div!</div>
     9 <iframe id = "frame" frameborder="0" scrolling="no"
    10 style="left:0;position:absolute;" src = "frame.html"></iframe>
    11 </body>
    12 </html>
    13 frame.html
    14 <html>
    15 <head>
    16 <title>this is a frame!</title>
    17 </head>
    18 <body>
    19 <div id = "div1">this is a div,too!</div>
    20 <label>input:</label>
    21 <input id = "input1"></input>
    22 </body>
    23 </html>
    
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class FameStudy {
    public static void main(String[] args) {
    WebDriver dr = new FirefoxDriver();
    String url = "\Your\Path\to\main.html";
    dr.get(url);
    //在 default content 定位 id="id1"的 div
    dr.findElement(By.id("id1"));
    //此时,没有进入到 id="frame"的 frame 中时,以下两句会报错
    dr.findElement(By.id("div1"));//报错
    Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)
    dr.findElement(By.id("input1"));//报错
    //进入 id="frame"的 frame 中,定位 id="div1"的 div 和id="input1"的输入框。
    dr.switchTo().frame("frame");
    dr.findElement(By.id("div1"));
    dr.findElement(By.id("input1"));
    //此时,没有跳出 frame,如果定位 default content 中的元素也会报错。
    dr.findElement(By.id("id1"));//报错
    //跳出 frame,进入 default content;重新定位 id="id1"的 div
    dr.switchTo().defaultContent();
    dr.findElement(By.id("id1"));
    }
    }
    
    
    switch_to 方法会 new1 个 TargetLocator 对象,使用该对象的 frame 方法可以将当前识别
    的”主体”移动到需要定位的 frame 上去。
  • 相关阅读:
    Linux的iptables和netfilter
    adb安装电视apk
    令牌桶实现服务器限流
    观察者模式代码实现
    Windows系统安装Oracle 11g 数据库
    Gitlab安装后 启动之后报错502
    Git两库合并历史记录
    Maven打包时指定对应环境的配置文件
    HierarchicalDataTemplateGridControl
    自定义CommandHandler
  • 原文地址:https://www.cnblogs.com/by170628/p/7120916.html
Copyright © 2020-2023  润新知