一、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());
=================================慄 子=====================================css
一、id 獲取id 的屬性值html
二、starts-with 顧名思義,匹配一個屬性開始位置的關鍵字 -- 模糊定位java
三、contains 匹配一個屬性值中包含的字符串 -- 模糊定位node
四、text() 函數文本定位函數
五、last() 函數位置定位spa
egcode
<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>orm
//a[text()='把百度設爲主頁']htm
/A/B/C[last()] 表示A元素→B元素→C元素的最後一個子元素,獲得id值爲e2的E元素