轉載別人的,原文鏈接如下,我在這裏做個備忘
原文:https://blog.csdn.net/hou_angela/article/details/80305828
一、XPath是什麼:
XPath是一種在XML文檔中查找指定信息的語言;可用於在XML中進行元素和屬性的遍歷
XPath使用表達式來選取XML中的節點或節點集;
二、XPath常用定位方法:
1. 通過元素本身的唯一屬性定位
方法:找到目標元素所在的”精準元素“即唯一標識屬性,使用此屬性定位
1.1 通過id屬性定位
例:find_element_by_xpath("//input[@id='input']") #@後跟屬性,可以是任何屬性
1.2 通過name屬性定位
例:find_element_by_xpath("//div[@name='q']")
2. 通過上一級目錄的唯一屬性定位
方法:目標元素沒有唯一屬性,則去找到與目標元素相近的上級目錄中”唯一元素“作爲起始位置,然後根據此相對位置逐層往子目錄編寫到目標位置
例:find_element_by_xpath("//span[@id='input-container']/input")
find_element_by_xpath("//div[@id='hd']/form/span/input")
find_element_by_xpath("//div[@name='q']/form/span/input")
3. xpath做布爾邏輯運算
find_element_by_xpath("//div[@id='hd' or @name='q']")
4. 雙條件同時過濾
find_element_by_xpath("//div[@id='hd'][@name='q'")
5.目錄元素存在層級關係
例1: find_element_by_xpath("//ul[@class='app-list']/li[contains(@class,'safe')]/div")
例2:定位上一層再定位目標元素(定位dl再定位dt)
find_element_by_xpath("//form[@id='J_login_form]/dl/dt/input[@id='J_password']")
6. 模糊定位
6.1 contains 方法(包含)
find_element_by_xpath("//a[contains(@name,'trnews')]")
6.2 start-with方法(以XX開頭)
find_element_by_xpath("//a[start-with(@href,'http')]")
6.3 text方法
find_element_by_xpath("//a[contains(text(),'新聞')]") 查找超鏈接元素的文本內容
find_element_by_xpath("//*[text()='新聞']") 查找所有內容爲退出二字的元素
7、xpath的一些包含邏輯的用法
//*[count(XXX)=2] //統計XXX元素個數=2的節點
//*[local-name()='xxx'] //找到tag爲xxx的元素
//*[starts-with(local-name(),'x')] //找到所有tag以x開頭的元素
//*[contains(local-name(),'x')] //找到所有tag包含x的元素
//*[string-length(local-name())=3] //找到所有tag長度爲3的元素
//xxx | //yyy //多個路徑查找