絕對路徑選擇

從根節點開始的,到某個節點,每層都依次寫下來,每層之間用 / 分隔的表示式,就是某元素的 絕對路徑
  • Xpath : /html/body/div
  • CSS : html>body>div

相對路徑選擇

選擇所有div元素裡面的子節點p
  • Xpath : //div//p
  • CSS :
    1. 選擇直接子元素(父元素是div的p元素)div>p
    2. 選擇後代子元素(div元素裡的所有p元素)div p

萬用字元*

選擇所有div節點的所有直接子節點
  • Xpath : //div/*
  • CSS : div>*

根據屬性選擇

選擇所有class為a的b元素
  • Xpath : //b[@class='a']
  • CSS : .a
選擇style屬性為color的所有元素
  • Xpath : //*[@style='color']
  • CSS : [style='color']
選擇a屬性包含b的所有元素
  • Xpath : //*[contains(@a,'b')]
  • CSS : [a*='b']
選擇a屬性開頭為b的所有元素
  • Xpath : //*[starts-with(@a,'b')]
  • CSS : [a^='b']
選擇a屬性結尾為b的所有元素(xpath2.0語法,瀏覽器不支援)
  • Xpath : //*[ends-with(@a,'b')]
  • CSS : [a$='b']
選擇a屬性包含a1,b屬性開頭b1,c屬性結尾為c1的d元素
  • CSS : d[a*='a1'][b^='b1'][c$='c1']

按次序選擇元素

選擇父元素為div中的p型別第2個子元素
  • Xpath : //div/p[2]
  • CSS : div p:nth-child(2)
選擇父元素為div的第2個子元素
  • Xpath : //div/*[2]
  • CSS : div :nth-child(2)
選取p型別倒數第2個子元素
  • Xpath : //p[last()-1]
  • CSS : p:nth-last-child(2)
選擇a元素的第n個p子節點
  • CSS : a p:nth-of-type(n)
選擇a元素的倒數第n個p子節點
  • CSS : a p:nth-last-of-type(n)
選擇a元素的偶數子節點
  • CSS : a p:nth-of-type(n)
選擇a元素的奇數子節點
  • CSS : a :nth-child(even)
選擇a元素的p型別的偶數子節點
  • CSS : a p:nth-of-type(even)
選擇a元素的p型別的奇數子節點
  • CSS : a p:nth-of-type(even)

按範圍選擇元素

選取option型別第1到2個子元素
  • Xpath : //option[position()<=2]
選擇class屬性為a的前3個子元素
  • Xpath : //*[@class='a']/*[position()<=3]
選擇class屬性為a的後3個子元素
  • Xpath : //*[@class='a']/*[position()>=last()-2]

組選擇

選所有class為a的元素,和所有id為b的元素
  • Xpath : //*[@class='a'] | //*[@id='b']
  • CSS : .a , #b

根據子節點選擇父節點

父節點沒有特徵,但子節點有特徵時,可通過子節點定位父節點
查詢後2代元素包含a元素的節點
  • Xpath : //a/../..

兄弟節點選擇

選擇 class 為 a 的元素的所有後續兄弟節點
  • Xpath : //*[@class='a']/following-sibling::*
  • CSS : .a ~ *
選擇 class 為 a 的元素的所有前置兄弟節點
  • Xpath : //*[@class='a']/preceding-sibling::*
  • CSS : 不支援