selenium实践-用css去定位元素

               

一直以来都用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是否正确。


           

猜你喜欢

转载自blog.csdn.net/qq_44884203/article/details/89087474
今日推荐