在使用selenium webdriver進行元素定位時,通常使用findElement或findElements方法結合By類返回的元素句柄來定位元素。
其中By類的常用定位方式共八種,現分別介紹如下。
1. By.name()
假設我們要測試的頁面源碼如下:
<button id="gbqfba" aria-label="Google Search" name="btnK" class="gbqfba"><span id="gbqfsa">Google Search</span></button>
當我們要用name屬性來引用這個button并點擊它時,代碼如下:
1 public class SearchButtonByName {
2 public static void main(String[] args){
3 WebDriver driver = new FirefoxDriver();
4 driver.get("http://www.forexample.com");
5 WebElement searchBox = driver.findElement(By.name("btnK"));
6 searchBox.click();
7 }
8 }
2. By.id()
1 public class SearchButtonById {
2
3 public static void main(String[] args){
4
5 WebDriver driver = new FirefoxDriver();
6
7 driver.get("http://www.forexample.com");
8
9 WebElement searchBox = driver.findElement(By.id("gbqfba"));
10
11 searchBox.click();
12
13 }
14
15 }
3. By.tagName()
該方法可以通過元素的標簽名稱來查找元素。該方法跟之前兩個方法的區(qū)別是,這個方法搜索到的元素通常不止一個,所以一般建議結合使用findElements方法來使用。比如我們現在要查找頁面上有多少個button,可以用button這個tagName來進行查找,代碼如下:
public class SearchPageByTagName{
public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.get("http://www.forexample.com");
List<WebElement> buttons = driver.findElements(By.tagName("button"));
System.out.println(buttons.size()); //打印出button的個數
}
}
另外,在使用tagName方法進行定位時,還有一個地方需要注意的是,通常有些HTML元素的tagName是相同的
從圖中我們可以看到,單選框、復選框、文本框和密碼框的元素標簽都是input,此時單靠tagName無法準確地得到我們想要的元素,需要結合type屬性才能過濾出我們要的元素。示例代碼如下:
1 public class SearchElementsByTagName{
2
3 public static void main(String[] args){
4
5 WebDriver driver = new FirefoxDriver();
6
7 driver.get("http://www.forexample.com");
8
9 List<WebElement> allInputs = driver.findElements(By.tagName("input"));
10
11 //只打印所有文本框的值
12
13 for(WebElement e: allInputs){
14
15 if (e.getAttribute(“type”).equals(“text”)){
16
17 System.out.println(e.getText().toString()); //打印出每個文本框里的值
18
19 }
20
21 }
22
23 }
24
25 }