天天看點

xpath定位中詳解id 、starts-with、contains、text()和last() 的用法 複制代碼

1、XPATH使用方法
使用XPATH有如下幾種方法定位元素(相比CSS選擇器,方法稍微多一點):
a、通過絕對路徑定位元素(不推薦!)
WebElement ele = driver.findElement(By.xpath("html/body/div/form/input"));
b、通過相對路徑定位元素
WebElement ele = driver.findElement(By.xpath("//input"));
c、使用索引定位元素
WebElement ele = driver.findElement(By.xpath("//input[4]"));
d、使用XPATH及屬性值定位元素
WebElement ele = driver.findElement(By.xpath("//input[@id='fuck']"));
//其他方法(看字面意思應該能了解吧)
WebElement ele = driver.findElement(By.xpath("//input[@type='submit'][@name='fuck']"));
WebElement ele = driver.findElement(By.xpath("//input[@type='submit' and @name='fuck']"));
WebElement ele = driver.findElement(By.xpath("//input[@type='submit' or @name='fuck']"));
e、使用XPATH及屬性名稱定位元素   元素屬性類型:@id 、@name、@type、@class、@tittle
//查找所有input标簽中含有type屬性的元素
WebElement ele = driver.findElement(By.xpath("//input[@type]"));
f、部分屬性值比對
WebElement ele = driver.findElement(By.xpath("//input[start-with(@id,'fuck')]"));//比對id以fuck開頭的元素,id='fuckyou'
WebElement ele = driver.findElement(By.xpath("//input[ends-with(@id,'fuck')]"));//比對id以fuck結尾的元素,id='youfuck'
WebElement ele = driver.findElement(By.xpath("//input[contains(@id,'fuck')]"));//比對id中含有fuck的元素,id='youfuckyou'
g、使用任意值來比對屬性及元素
WebElement ele = driver.findElement(By.xpath("//input[@*='fuck']"));//比對所有input元素中含有屬性的值為fuck的元素
元素定位總結

//注:本專題隻介紹java版
//By id
WebElement ele = driver.findElement(By.id());
//By Name
WebElement ele = driver.findElement(By.id());
//By className
WebElement ele = driver.findElement(By.className());
//By tabName
WebElement ele = driver.findElement(By.tagName());
//By linkText
WebElement ele = driver.findElement(By.linkText());
//By partialLinkText
WebElement ele = driver.findElement(By.partialLinkText());//通過部分文本定位連接配接
//By cssSelector
WebElement ele = driver.findElement(By.cssSelector());
//By XPATH
WebElement ele = driver.findElement(By.xpath());
           

1、id 擷取id 的屬性值

2、starts-with 顧名思義,比對一個屬性開始位置的關鍵字 – 模糊定位

3、contains 比對一個屬性值中包含的字元串 – 模糊定位

4、text() 函數文本定位

5、last() 函數位置定位

eg:

<input id="su" class="bg s_btn btnhover" value="百度一下" type="submit"/>
//*[@id='su']      擷取id 的屬性為'su' 的值
或
//input[contains(@class,'bg s_btn')]
           
<a class="lb" href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login" onclick="return false;">登入</a>
//a[starts-with(@name,'tj_lo')]     屬性模糊定位
//a[contains(@name,'tj_lo')]     屬性模糊定位
           
<a href="http://www.baidu.com">百度搜尋</a>
//a[text()='百度搜尋'] 
或
//a[contains(text(),"搜尋")]    --文本模糊定位

<a id="setf" href="//www.baidu.com/cache/sethelp/help.html" onmousedown="return ns_c({'fm':'behs','tab':'favorites','pos':0})" target="_blank">把百度設為首頁</a>

//a[text()='把百度設為首頁']
           

繼續閱讀