元素定位

Selenium WebDriver提供一个先进的技术来定位web页面元素。Selenium功能丰富的API提供了多个定位策略:ID、Name、Xpath、CSS选择器等等。我们也可以执行自定义的定位策略来定位元素。

善于使用浏览器工具来检查页面元素结构
无论你使用哪种浏览器测试,都有一款合适的工具辅助你分析页面
1、Firefox的Firebug插件
2、Chrome内置的开发者工具
3、Internet Explorer自带的开发者工具
1、使用findElement方法定位元素
Selenium Webdriver定位元素通过使用findElement()和findElements()方法。findElememt()方法返回一个基于指定查找条件的WebElement对象或是抛出一个没有找到符合条件元素的异常。
findElements()方法会返回匹配指定查询条件的WebElements的集合,如果没有找到则返回为空。
查询方法会将By实例作为参数传入。Selenium WebDriver提供了By类来支持各种查询策略。
我们先来看一个例子。
百度首页的搜索框,通过开发者工具我们可以看到搜索框具有的属性:
<input type="text" name="wd" id="kw" maxlength="100" style="width:474px;" autocomplete="off">

所以我们可以用id属性、name属性或则xpath来定位这个搜索框
//id
WebElement content_id = driver.findElement(By.id("kw"));
//name
WebElement content_name = driver.finElement(By.Name("wd"));
//xpath
WebElement content_xpath = driver.finElement(By.Xpath("//input[@id='kw'] "));
//or
//WebElement content_xpath = driver.finElement(By.Xpath("//input[@name='wd'] "));

2、使用findElements方法定位元素
测试需求以百度首页为例,我们要验证百度首页导航链接的数量,并打印出他们的超链接地址
baidu
程序清单如下:
package com.example.tests; 
import static org.junit.Assert.*; 
import java.util.*; 
import org.junit.*; 
import org.openqa.selenium.*; 
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Test{ 
 @Test 
 public void test() {     
     WebDriver driver = new InternetExplorerDriver(); 
     driver.get("http://www.baidu.com"); 
     List<WebElement> links = driver.findElements(By.cssSelector("#nv a")); 
     //验证链接数量 
     assertEquals(10, links.size()); 
     //打印href属性 
     for (int i = 0; i < links.size(); i++) { 
    System.out.println(links.get(i).getAttribute("href")); 
  }     
  driver.close(); 
 } 
}

执行后打印结果如下:
http://news.baidu.com/ 
http://tieba.baidu.com/ 
http://zhidao.baidu.com/ 
http://music.baidu.com/ 
http://image.baidu.com/ 
http://video.baidu.com/ 
http://map.baidu.com/ 
http://baike.baidu.com/ 
http://wenku.baidu.com/ 
http://www.baidu.com/more/

findElements()方法返回所有匹配定位策略的WebElement的集合,我们可以使用java中List类来创建WebElements的实例 ,List类中的size()方法会告诉你这个集合中元素的总数量。 通过for循环将得到List中所有的元素,再调用getAttribute()方法得到元素的属性。

猜你喜欢

转载自865325772.iteye.com/blog/2051665