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是否正確。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章