xpath寫法:
絕對路徑:以/開始,逐個增加節點用/分割
特點:不能跨級、類似css中的直接子元素選擇器
相對路徑:用兩個斜杠 // 如 //div//p//a
通配符:xpath也有通配符 *
比如 所有的節點 //div/* 選擇div下面所有的直接子元素
根據屬性和屬性的值的選擇 ----------- 比如 id 、 class='xxx'等
比如 //*[@style] 選擇所有具有style屬性的元素 ----- 注意前面必須有個@
比如 //p[@spec='len2'] 選擇所有具有spec值len2的元素 -----等價於------- css中的p[speec='len2']
比如 根據id選擇 //div[@id='food']
比如 根據class選擇 //div[@class='cheese']
模糊的屬性值定位元素:
fn:contains(string1,string2)寫法 ------- contains() 包含
比如 //*[contains(@style, 'margin-top')]
fn:starts-with(string1,string2)寫法 -------- starts-with() 以什么開頭
比如 //*[starts-with(@style, 'margin-top')]
:nth-child(n)寫法 ----- 選擇父元素下第幾個子元素
比如 #food :nth-child(2)
:nth-of-type(n)寫法 ------- 選擇屬於父元素下第幾個元素的每個元素
比如 #food>p:nth-of-type(2)
子元素選擇?:
選擇屬於其父元素的第n個某個類型的子元素
如 //*[@id='food']/p[1] 等價於 #food>p:nth-of-type(1)
選擇屬於其父元素的倒數第n個某個類型的子元素
如 //span[last()-1]
//*[@id='food']/span[last()]
還有像 :nth-last-child(n)
nth-last-of-type(n)
子元素選擇:
選擇屬於其父元素的第n個子元素(基於所有類型元素)
如://*[@id='food']/*[position()=2]
支持其他的 比較操作符
如://*[@id='food']/*[position() < 3]
選擇屬於其父元素的倒數第n個子元素
如://*[@id='food']/*[position()=last()-1]
組元素:
在xpath中,用 | 來隔開, 如: //p | //button
相鄰兄弟選擇器:
比如: //*[@id='food']/following-sibling::div 找當前元素相鄰的元素 往下找
比如: //*[@id='food']/preceding-sinling::div 找當前元素相鄰的元素怒 網上找
定位到上級元素:
比如: //div/..
//div//*[id='food']/..
xpath擅長的:
選擇父節點 ..符號
position函數, 結合比較操作符
注意:如果在寫代碼時,driver.find_elements_by_xpath('.//p') 相對路徑時,前面必須要加上點。