一直以来都用xpath去识别元素,xpath确识方便又实用,但有时会发现它要写很长很长,对于有些元素,用css去定位,可能更加方便。
假设有如下的HTML页面:
line 1 <html>
line 2 <body>
line 3 <form id= "loginForm" >
line 4 <input name= "username" type= "text" />
line 5 <input name= "password" type= "password" />
line 6 <input name= "continue" type= "submit" value= "Login" />
line 7 <a href= "continue.html" >Continue</a>
line 8 </form>
line 9 </body>
line 10 <html>
通过XPath定位
例如:
driver.click("xpath=/html/body/form[1]")。如果使用相对路径,则可以省略"xpath=":
driver.click("//form[1]");
driver.click("//form[@id='loginForm']");
driver.click("//form[@id='loginForm']/input[1]");
driver.click("//input[@name=‘username’]");
通过css定位
例如:
driver.click("css=form#loginForm");
driver.click('css=input[name="username"]');
driver.click("css=#loginForm input:nth-child(2)");
怎么查看页面元素的各个属性呢?推荐使用Firefox的Firebug插件,可以自动生成指定元素的xpath和css。同时配合Firefinder,可以验证你的xpath和css是否正确。
2。Install Firefox的Firebug插件
open Firefox->工具-〉附加组件-〉搜素firebug
Install filebug and filefinder
3。在做一个项目的selenium测试,但是遇到一个问题,通过tape语句输入日期之后,到selenium运行到查询按钮的时候,
输入的日期却是不正确了。比如输入04102013,结果却04/02/13__。输入04/10/2013,结果却是04/10/20。
后来深入的研究了日期输入框的行为,原来是系统在js上做了一些特殊的处理。光标进入时,把格式掩码(如/)去掉,
显示数字,光标离开之后,进行格式掩码处理。 并且限制该输入框的最大输入长度为8。因此,才造成上面的几种错误。
所以,我们就采用下面的作法,模拟光标的进入,赋值,光标离开。
selenium.focus("id=condition.orderNo"); //id=condition.fromDate的上一个项目
selenium.keyPressNative("09"); //模拟键入tab键
selenium.focus("id=condition.fromDate"); // 设光标
selenium.type("id=condition.fromDate", "04102013"); //赋值
selenium.focus("id=condition.fromDate"); //设光标
selenium.keyPressNative("09"); //模拟键入tab键
origin: http://blog.csdn.net/xinwang/article/details/16842991