您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 > Selenium
Java Selenium (五) 元素定位大全
作者:小坦克 發(fā)布時間:[ 2017/7/12 15:05:57 ] 推薦標簽:Selenium 功能測試工具

  通過Name查找元素:By.name()
  以豆瓣網的主頁搜索框為例, 其搜索框的HTML代碼如下, 它name是: q
  <input type="text" autocomplete="off" name="q" placeholder="書籍、電影、音樂、小組、小站、成員" size="12" maxlength="60">
  WebDriver中通過name查找豆瓣主頁上的搜索框的Java代碼如下:
  WebDriver driver  = new FirefoxDriver();
  driver.get("http://www.douban.com");
   
  WebElement searchBox = driver.findElement(By.name("q"));
  searchBox.sendKeys("小坦克");
  searchBox.submit();
  通過TagName查找元素: By.tagName()
  通過tagName來搜索元素的時候,會返回多個元素. 因此需要使用findElements()
  WebDriver driver  = new FirefoxDriver();
  driver.get("http://www.cnblogs.com");
   
  List<WebElement> buttons = driver.findElements(By.tagName("div"));
  System.out.println("Button:" + buttons.size());
  注意: 如果使用tagName, 要注意很多HTML元素的tagName是相同的,
  比如單選框,復選框, 文本框,密碼框.這些元素標簽都是input. 此時單靠tagName無法精確獲取我們想要的元素, 還需要結合type屬性,才能過濾出我們要的元素
  WebDriver driver  = new FirefoxDriver();
          driver.get("http://www.cnblogs.com");
           
          List<WebElement> buttons = driver.findElements(By.tagName("input"));
          for (WebElement webElement : buttons) {
              if (webElement.getAttribute("type").equals("text")) {
                  System.out.println("input text is :" + webElement.getText());
              }
          }
  通過ClassName 查找元素 By.className
  以淘寶網的主頁搜索為例, 其搜索框的HTML代碼如下: class=”search-combobox-input”
  <input autocomplete="off" autofocus="true" accesskey="s" aria-label="請輸入搜索文字" name="q" id="q" class="search-combobox-input" aria-haspopup="true" aria-combobox="list" role="combobox" x-webkit-grammar="builtin:translate" tabindex="0">
  Java 示例代碼如下
  WebDriver driver  = new FirefoxDriver();
          driver.get("http://www.taobao.com");
          Thread.sleep(15000);
          WebElement searchBox = driver.findElement(By.className("search-combobox-input"));
  
          searchBox.sendKeys("羽絨服");
          searchBox.submit();
  注意:使用className 來進行元素定位時, 有時會碰到一個
  通過LinkText查找元素 By.linkText();
  直接通過超鏈接上的文字信息來定位元素:例如
  <a href="https://passport.baidu.com/v2/?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login" class="lb" onclick="return false;">登錄</a>
  HTML 代碼如下
  WebDriver driver  = new FirefoxDriver();
  driver.get("http://www.baidu.com");
  WebElement loginLink = driver.findElement(By.linkText("登錄"));
  loginLink.click();
  通過PartialLinkText 查找元素 By.partialLinkText()
  此方法是上一個方法的加強版, 單你只想用一些關鍵字匹配的時候,可以使用這個方法,通過部分超鏈接文字來定位元素
  HTML 代碼如下
  WebDriver driver  = new FirefoxDriver();
  driver.get("http://www.baidu.com");
  WebElement loginLink = driver.findElement(By.partialLinkText("登"));
  loginLink.click();
  注意:用這種方法定位時,可能會引起的問題是,當你的頁面中不知一個超鏈接包含“等”時,findElement方法只會返回第一個查找到的元素,而不會返回所有符合條件的元素
  如果你想要獲得所有符合條件的元素,還是只能用findElements方法。

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