您的位置:首页 > 其它

Selenium + Webdriver 学习(四) 元素定位方法

2014-04-09 10:35 399 查看
selenium-webdriver提供了强大的元素定位方法,支持以下三种方法。

单个对象的定位方法
多个对象的定位方法
层级定位

定位单个元素
在定位单个元素时,selenium-webdriver提示了如下一些方法对元素进行定位。

By.className(className))
By.cssSelector(selector)
By.id(id)
By.linkText(linkText)
By.name(name)
By.partialLinkText(linkText)
By.tagName(name)
By.xpath(xpathExpression)

注意:selenium-webdriver通过findElement()\findElements()等find方法调用"By"对象来定位 和查询元素。By类只是提供查询的方式进行分类。findElement返回一个元素对象否则抛出异常,findElements返回符合条件的元素 List,如果不存在符合条件的就返回一个空的list。
Java代码:

/*** This class is about Location Elements.
* @author annie.wang
*/
package com.annie.test;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ElemLocation {
public static void main(String[] args) {
// TODO Auto-generated method stub

// TODO Auto-generated method stub
WebDriver dr = new FirefoxDriver();
dr.get("https://accounts.google.com/ServiceLogin?hl=zh-CN&continue=https://www.google.com.hk/");
/**通过id获取元素 */
WebElement element = dr.findElement(By.id("Email"));
/**获取对象属性*/
System.out.println(element.getAttribute("placeholder"));
/**通过name获取元素 */
WebElement element02 =dr.findElement(By.name("Passwd"));
System.out.println(element02.getTagName());
/**通过CSS选择器获取元素*/
WebElement element03 = dr.findElement(By.cssSelector("#Email"));
/**使用其他方式定位在定位link元素的时候,
* 可以使用link和link_text属性;
* 另外还可以使用tag_name属性定位任意元素**/
/**定位多个元素*/
List<WebElement> elements = dr.findElements(By.tagName("input"));   //定位到所有<input>标签的元素,然后输出他们的id
for (WebElement e : elements){
System.out.println(e.getAttribute("id"));
}

System.out.println("----------------------");
/** 层级定位
* 层级定位的思想是先定位父元素,
* 然后再从父元素中精确定位出其我们需要选取的子元素。
*/

WebDriver  driver = new FirefoxDriver();
driver.get("http://www.51.com");

//定位class为"login"的div,然后再取得它下面的所有label,并打印出他们的值
WebElement eles = driver.findElement(By.className("login"));
List<WebElement> el = eles.findElements(By.tagName("label"));
for(WebElement e : el)
System.out.println(e.getText());
}

}


结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: