1. 程式人生 > >使用Xpath定位元素(和元素定位相關的Xpath語法)

使用Xpath定位元素(和元素定位相關的Xpath語法)

本文主要講述Xpath語法中,和元素定位相關的語法

第一種方法:通過絕對路徑做定位(相信大家不會使用這種方式)

By.xpath("html/body/div/form/input")

第二種方法:通過相對路徑做定位

兩個斜槓代表相對路徑

By.xpath("//input//div")

第三種方法:通過元素索引定位

By.xpath("//input[4]")

第四種方法:使用xpath+節點屬性定位(結合第2、第3中方法可以使用)

By.xpath("//input[@id='kw1']")
By.xpath("//input[@type='name' and @name='kw1']")

第五種方法:使用部分屬性值匹配(最強大的方法)

By.xpath("//input[start-with(@id,'nice')]")
By.xpath("//input[ends-with(@id,'很漂亮')]")
By.xpath("//input[contains(@id,'那麼美')]")

第六種方法:使用前集中方法的組合

By.xpath("//input[@id='kw1']//input[start-with(@id,'nice']/div[1]/form[3])