敏捷验收测试必备技能:Selenium WebDriver常用八种元素定位方法使用举例 Selenium WebDriver常用八种元素定位方法使用举例

Selenium WebDriver常用八种元素定位方法使用举例

  • By.name() 
使用Web元素名查询定位HTML元素 
举例说明: 

页面元素HTML代码

 <input name="email" autocomplete="off" placeholder="请填写邮箱" class="el-input__inner" >

WebDriver元素定位代码

driver.findElement(By.name("email")).sendKeys("[email protected]");

  • By.id()

使用Web元素ID查询定位页面元素 
举例说明: 

页面元素HTML代码

<button id="loginbtn" type="button" class="el-button el-button--primary">
            <span>登录</span>
 </button>

WebDriver元素定位代码

driver.findElement(By.id("loginbtn")).click();

  • By.tagName()

使用Web元素标签名称查询定位元素 

页面元素HTML代码

<button id="loginbtn" type="button" class="el-button el-button--primary">
                <span>登录</span>
 </button>

WebDriver元素定位代码

driver.findElement(By.tagName("button")).click();
  • By.className()

使用Web元素的css类定位元素

页面元素HTML代码

<button id="loginbtn" type="button" class="el-button el-button--primary">
        <span>登录</span>
</button> 

WebDriver元素定位代码

driver.findElement(By.className(“el-button el-button--primary”)).click();   

  • By.linkText()

使用Web元素超链接文本定位元素

页面元素HTML代码

<a href="http://gitbook.cn/gitchat/column/5aebe3ea4eb5f845a0773ddb#catalog" rel="nofollow">十招玩转敏捷测试</a>

WebDriver元素定位代码

driver.findElement(By.linkText("十招玩转敏捷测试")).click();   

  • By.partialLinkText()

使用Web元素的部分文本模糊定位元素

页面元素HTML代码

<a href="http://gitbook.cn/gitchat/column/5aebe3ea4eb5f845a0773ddb#catalog" rel="nofollow">十招玩转敏捷测试</a>

WebDriver元素定位代码

driver.findElement(By..partialLinkText("敏捷测试")).click();

  • By.xpath()

使用页面元素在HTML的dom路径定位元素

页面元素HTML代码

<div id="login-box" class="login-box">
            <form >
              <h3 class="title"><span>登录</span></h3>
              <label for="email" class="el-form-item__label">邮箱</label>
              <input name="email" autocomplete="off" placeholder="请填写邮箱" class="el-input__inner" >
            </form>
 </div>

WebDriver元素定位代码

driver.findElement(By.xpath("//*[@id='login-box']/from/input[0]")).sendKeys("[email protected]");

  • By.cssSelector()

cssSelector这种元素定位方式跟xpath比较类似,但执行速度较快,而且各种浏览器对它的支持也比较好。

页面元素HTML代码

<button id="loginbtn" type="button" class="el-button el-button--primary">
        <span>登录</span>
</button>

WebDriver元素定位代码

driver.findElement(By.cssSelector(“button.el-button el-button--primary”)).click();    

另外一种定位代码是

driver.findElement(By.cssSelector(“#loginbtn”)).click();

GITBOOK 达人课: 十招玩转敏捷测试



敏捷社区微信公众号:

微信.jpg

敏捷测试微信公众号:

qrcode_for_gh_2d53be29b2f6_258.jpg

猜你喜欢

转载自blog.csdn.net/winteroak/article/details/80680014