目录

(四)通过id去定位页面上的元素

关于定位

UI的自动化测试的主要操作就是找到页面上的元素并且操作元素。找到元素一般有2个目的

  • 操作元素: 比如点击,输入内容之类的
  • 获取这个元素的某些属性: 比如获取一个段落元素(p)的内容,通过这个内容去验证测试是否达到了预期的效果(断言)

定位方式

selenium的javascript binding支持下面一些定位方法

  • By.className( name )

  • By.css( selector )

  • By.id( id )

  • By.js( script, …var_args )

  • By.linkText( text )

  • By.name( name )

  • By.partialLinkText( text )

  • By.xpath( xpath )

在这些定位方式里,最简单最常用的定位方式就是通过元素的id进行定位

目的

  • 熟悉selenium webdriver 定位方式
  • 学会通过id属性去定位元素
  • 学会使用sendKeys()方法

练习对象

我们使用html5-test-page作为我们的练习对象。

将html代码拷贝一份并保存到本地,文件名为index.html

场景

我们将使用id定位下图所示的输入框,并输入一些内容

https://ooo.0o0.ooo/2017/06/29/5954b8e6b038a.png

代码

新建文件by_id.js,并键入下面的内容。

var path = require('path');
var webdriver = require('selenium-webdriver'),
  By = webdriver.By;

var testFile = "file://" + path.join(__dirname,  "index.html")

var dr = new webdriver.Builder().forBrowser('chrome').build();
dr.get(testFile)

dr.findElement(By.id('input__text')).sendKeys('测试教程网');
dr.findElement(By.id('input__password')).sendKeys('password');
dr.findElement(By.id('input__webaddress')).sendKeys('http://www.itest.info');
dr.findElement(By.id('input__emailaddress')).sendKeys('service@itest.info');
dr.findElement(By.id('input__phone')).sendKeys('13888888888');
dr.findElement(By.id('input__search')).sendKeys('keywords');
dr.findElement(By.id('input__text2')).sendKeys('6666666');
dr.findElement(By.id('input__text3')).sendKeys('should be error');
dr.findElement(By.id('input__text4')).sendKeys('should be valid');

运行结果

如下图所示

https://ooo.0o0.ooo/2017/06/29/5954bc8b76c1e.png

总结

对于形如<input id="input__text" type="text" placeholder="Text Input">有id属性的元素,我们可以使用dr.findElement(By.id('input__text'))来定位。

原始封面

https://images.unsplash.com/photo-1464983953574-0892a716854b?w=300