selenium之Xpath定位


1. 絕對定位:

driver.find_element_by_xpath("/html/body/div[x]/form/input") x 代表第x個 div標簽,注意,索引從1開始而不是0

2.相對路徑:

driver.find_element_by_xpath("//input[x]") 定位第x個input標簽,[x]可以省略,默認為第一個

3.標簽屬性定位: 

driver.find_element_by_xpath("//a[@href='/industryMall/hall/industryIndex.ht']")
driver.find_element_by_xpath("//input[@value='確定']")
driver.find_element_by_xpath("//div[@class = 'submit']/input")
driver.find_element_by_xpath("//input[@type='name' and @name='kw1']")

driver.find_element_by_xpath("//標簽[contains(text(),'文本值')]") 

driver.find_element_by_xpath("//input[contains(text(),'型號')]")    

driver.find_element_by_xpath(“//a[contains(@href, ‘logout’)]”)  

a.starts-with      例子: input[starts-with(@id,'ctrl')]                  解析:匹配以ctrl開始的屬性值

b.ends-with        例子:input[ends-with(@id,'_userName')]     解析:匹配以userName結尾的屬性值   好像不行,經常報錯,不推薦

c.contains()        例子:Input[contains(@id,'userName')]         解析:匹配含有userName屬性值

driver.find_element_by_xpath("//input[@id='kw1']//input[start-with(@id,'nice']/div[1]/form[3])  如果上面的單一方法不能完成定位,也可以采取組合式定位

4.Xpath軸方式定位元素 

     1、child  選取當前節點的所有子元素

           driver.find_element_by_xpath("//div[@id='B']/child::div")

     2、parent  選取當前節點的父節點

           driver.find_element_by_xpath("//div[@id='C']/parent::*/parent::div")

           driver.find_element_by_xpath("//div[@id='C']/..")   后面兩點也代表上一級的父節點

     3、descendant選取當前節點的所有后代元素(子、孫等)

           "//form[@id='form']/descendant::input[@id='su']"

     4、ancestor  選取當前節點的所有先輩(父、祖父等)

          //*[@id='%s']/ancestor::td/preceding-sibling::td[1]

     5、preceding-sibling選取當前節點之前的所有同級節點

          driver.find_element_by_xpath("//div[@id='D']/preceding-sibling::div[1]").text

     6、following-sibling選取當前節點之后的所有同級節點

           driver.find_element_by_xpath("//td[contains(text(),’17051915200001’)]/following-sibling::td[8]/a[@class='link']")

     7、preceding   選取文檔中當前節點的開始標簽之前的所有節點

           //p[text()='出售方信息']/preceding::div[contains(text(),'擬定網簽價')]

     8、following   選取文檔中當前節點的結束標簽之后的所有節點

          //td[@width='50%']/following::div[contains(text(),'行政區域')]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM