Selenium WebDriver---weiwan

命令和操作

基于WebDriver driver = new FirefoxDriver();创建的一个driver实例:
1. 访问一个页面
第一件你想使用WebDriver做的事情肯定是访问一个页面,最基础的方法是调用“get”方法:

driver.get("http://www.google.com");
//或者下面的方法
driver.navigate().to("http://www.google.com");

WebDriver会自动等待到该页面完全加载才执行接下来的测试和脚本的执行。但是如果你的页面存在很多的AJAX加载,此时WebDriver是无法知道是否完成加载。检查此类页面是否加载完成,那么我们就需要Explicit和Implicit Wait(这两个将在后面文章解释)。

2.定位UI元素
WebDriver可以通过WebDriver实例来定位元素,任何语言库都含有“Find Element”和“Find Elements”的方法。第一个方法返回一个WebElement或者抛出异常。后者返回所有WebElement的列表,或者空列表。

获取和定位元素我们调用“By”方法。下面具体解释下“By”方法
a.By ID

<div id="coolestWidgetEvah">...</div>
WebElement element = driver.findElement(By.id("coolestWidgetEvah"));

b.By Class Name
这里的class指的是DOM中的元素,在实际使用过程中,我们也会发现很多DOM元素含有相同的class名

<div class="cheese">
    <span>Cheddar</span>
</div>
<div class="cheese">
    <span>Gouda</span>
</div>

List<WebElement> cheeses = driver.findElements(By.className("cheese"));

c.By Tag Name
DOM的Tag元素

<iframe src="..."></iframe>
WebElement frame = driver.findElement(By.tagName("iframe"));

d.By Name

<input name="cheese" type="text"/>
WebElement cheese = driver.findElement(By.name("cheese"));

e.By Link Text

<a href="http://www.google.com/search?q=cheese">cheese</a>>
WebElement cheese = driver.findElement(By.linkText("cheese"));

f.By Partial Link Text

<a href="http://www.google.com/search?q=cheese">search for cheese</a>>
WebElement cheese = driver.findElement(By.partialLinkText("cheese"));

g.By CSS

<div id="food">
    <span class="dairy">milk</span>
    <span class="dairy aged">cheese</span>
</div>
WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy aged"));

h.By XPATH
i.使用javascript
您可以执行任意JavaScript找到一个元素,只要你返回一个DOM元素,它会自动转换到一个WebElement对象。
jQuery的页面加载一个简单的例子:

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]"); 

寻求所有的页面上的input元素:

List<WebElement> labels = driver.findElements(By.tagName("label"));

List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(

      "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +

"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值