您的位置:軟件測(cè)試 > 開源軟件測(cè)試 > 開源功能測(cè)試工具 > Selenium
Selenium Webdriver元素定位的八種常用方式
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2015/11/5 13:47:10 ] 推薦標(biāo)簽:功能測(cè)試 軟件測(cè)試工具

  在使用selenium webdriver進(jìn)行元素定位時(shí),通常使用findElement或findElements方法結(jié)合By類返回的元素句柄來(lái)定位元素。
  其中By類的常用定位方式共八種,現(xiàn)分別介紹如下。
  1. By.name()
  假設(shè)我們要測(cè)試的頁(yè)面源碼如下:
  <button id="gbqfba" aria-label="Google Search" name="btnK" class="gbqfba"><span id="gbqfsa">Google Search</span></button>
  當(dāng)我們要用name屬性來(lái)引用這個(gè)button并點(diǎn)擊它時(shí),代碼如下:
  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()
  該方法可以通過元素的標(biāo)簽名稱來(lái)查找元素。該方法跟之前兩個(gè)方法的區(qū)別是,這個(gè)方法搜索到的元素通常不止一個(gè),所以一般建議結(jié)合使用findElements方法來(lái)使用。比如我們現(xiàn)在要查找頁(yè)面上有多少個(gè)button,可以用button這個(gè)tagName來(lái)進(jìn)行查找,代碼如下:
  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的個(gè)數(shù)
  }
  }
  另外,在使用tagName方法進(jìn)行定位時(shí),還有一個(gè)地方需要注意的是,通常有些HTML元素的tagName是相同的

  從圖中我們可以看到,單選框、復(fù)選框、文本框和密碼框的元素標(biāo)簽都是input,此時(shí)單靠tagName無(wú)法準(zhǔn)確地得到我們想要的元素,需要結(jié)合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());  //打印出每個(gè)文本框里的值
18
19                   }
20
21             }
22
23        }
24
25 }

上一頁(yè)12下一頁(yè)
軟件測(cè)試工具 | 聯(lián)系我們 | 投訴建議 | 誠(chéng)聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd