Selenium2 入门[2] —— WebDrive 简单的小例子,访问百度搜索内容

来源:互联网 发布:龙猫头像知乎 编辑:程序博客网 时间:2024/06/05 01:57
环境搭建详见之前的blog。

本例子是跳转至百度页面,待页面加载完毕后窗口最大化,然后搜索“试一试百度搜索”,最后在页面加载完毕后退出测试。

package demo.test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.base.Function;
 
public class testPara {
public WebDriver ffdirver;
public String url;
public String searchText;
@BeforeClass
public void BeforeClass(){
url = "http://www.baidu.com";
searchText = "试一试百度搜索";
//获取Firefox 驱动
ffdirver = new FirefoxDriver();
}
@Test
public void GoToLink(){
//跳转到url
ffdirver.get(url);
//等待页面加载完毕
waitForPageLoad();
//Firefox窗口最大化
ffdirver.manage().window().maximize();
//输入searchText到百度的搜索框中
ffdirver.findElement(By.xpath(".//*[@id='kw']")).sendKeys(searchText);
//点击搜索按钮
/*
* 使用WebDriver点击界面上Button元素时,如果当前Button元素被界面上其他元素遮住了,
* 或没出现在界面中(比如Button在页面底部,但是屏幕只能显示页面上半部分),
* 使用默认的WebElement.Click()可能会触发不了Click事件。
* 需加上((JavascriptExecutor)webDriver).executeScript("arguments[0].click();", webElement);
*/
WebElement button = ffdirver.findElement(By.xpath(".//*[@id='su']"));
((JavascriptExecutor)ffdirver).executeScript("arguments[0].click()", button);
}
@AfterClass
public void AfterClass()
{
System.out.println("hh");
//等待页面加载完毕
waitForPageLoad();
ffdirver.close();
}
/*
* 当发生页面跳转时,加一个wait方法等待page load 完成
* 方法是在某个时间段内判断document.readyState=complete?
*/
public void waitForPageLoad(){
Function<WebDriver,Boolean> waitFn = new Function<WebDriver,Boolean>(){
@Override
public Boolean apply(WebDriver driver){
return ((JavascriptExecutor)driver).executeScript("return document
.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(ffdirver, 30);
wait.until(waitFn);
}
 
}

0 0