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

环境搭建详见之前的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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值