1. CSS locator比XPath locator速度快,特別是在IE下面(IE沒有本身的XPath 解析器(Parser))css
2. 對於文本的處理xpath更強大使用, text()匹配的是顯示文本信息。函數
String locator_Xpath = "//*[contains(text(),'test')]";
但須要注意的是text()獲取的是當前元素的文本,不包括其子元素的文本。以下代碼text()獲得的結果是"Please click here"。但若是使用$("#id1").text()獲取的是"Memo Please click here",使用selenium獲取元素text也是"Memo Please click here"。spa
<div id="id1">
<span>Memo<span> Please click here </div>
3. 對於class屬性Css能直接匹配部分,而Xpath對於class跟普通屬性一致,使用字符串精確匹配,須要使用contains()函數才能匹配部分字符串code
<div class="class1 popup js-dragable alert-msg">
<div class ="class2 submit-box ">
<input class ="class3"/>
</div>
</div> String locator_Xpath="//div[@class='class1 popup js-dragable alert-msg']//input[@class='class3']"; String locator_Xpath="//div[contains(@class,'popup js-dragable alert-msg')]//input[@class='class3']"; String locator_Css = ".class1.js-dragable .class3"
4. 使用祖先元素屬性與當前元素屬性組合處理時blog
<div class="111">
<div>
<div>
<input class = "222"/>
</div>
</div>
</div> String locator_xpath="//div[@class='111'/*/*/*[@class='222']]";
String locator_xpath="//div[@class='111'//[@class='222']]" String locator_css = ".111 .222";
*注意兩個class之間有一個空格表示層級關係,且空格選擇全部層級的子元素,而>只選擇一代字符串
5.模糊匹配input
XPath | Css | |
選取屬性值中的部分string匹配 | //span[contains(@class,'popup-btn js-dragable')] | span[title*='456'] |
//input[starts-with(@name,'name1')] | input[name^='name1'] | |
//input[ends-with(@name,'name1')] | input[name$='name1'] | |
**ends-with() function is part of XPath 2.0 but browsers generally only support 1.0.selenium
6.多個屬性匹配string
xpath=//a[@class='name' and value='123']產品
css = a[.name][value='123']
7. 第n個子元素的選擇
<div class="category_depth_1 bnr">
<li><a href="/estore/kr/zh/c/1" class="on">護膚</a></li>
<li><a href="/estore/kr/zh/c/1" class="on">家電</a></li>
<li><a href="/estore/kr/zh/c/1" class="on">美妝</a></li>
<li><a href="/estore/kr/zh/c/1" class="on">母嬰</a></li>
<li><a href="/estore/kr/zh/c/1" class="on">電子產品</a></li>
</div> String locator_Xpath = "//*[@class="category_depth_1 bnr"]//li[1]" String locator_Css = ".category_depth_1.bnr li:first-child" String locator_Css = ".category_depth_1.bnr li:last-child" String locator_Css = ".category_depth_1.bnr li:nth-child(1)" #index都是從1開始
以上元素若是選擇點擊li元素有可能點擊不生效而選擇點擊a標籤,這個時候須要注意index仍是要標在li標籤後面 String locator_Xpath = "//*[@class="category_depth_1 bnr"]//li[1]/a" String locator_Css = ".category_depth_1.bnr li:first-child a" String locator_Css = ".category_depth_1.bnr li:last-child>a" String locator_Css = ".category_depth_1.bnr li:nth-child(1)>a"
8. 擁有某個屬性的元素
xpath= //*[@title]
css= *[title]
9. 擁有子元素a的P元素
xpath= //div[a]
css 不能實現
10. 匹配祖先元素
xpath= div[@id="id1"]//ancestor::tr//td
css 不能實現
11. 查找兄弟元素, Css只能查找元素後面的元素,不能向前找
xpath= //div[@class="class1"]//preceding-sibling::div[1]
xpath= //div[@class="class1"]//follow-sibling::div[1]
css= div.class1+div
12. 查找不包含not,以不包含display: none爲例
xpath= //div[@class="name" and not(contains(@style,"display: none"))]
css= div.name:not([style*='display: none'])