将页面元素封装,外部通过对应方法来调用,看如下代码,本文使用java编写
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class BaiduSeparatePage {
// 定义百度首页搜索的输入框
@FindBy(id = "kw")
@CacheLookup
private WebElement keyword_input;
// 定义百度首页搜索按扭
@FindBy(id = "su")
@CacheLookup
private WebElement search_button;
//定义测试地址
private final String url = "http://www.baidu.com";
WebDriver driver;
//创建一个构造函数,并启动firefox浏览器
public BaiduSeparatePage() {
driver = new FirefoxDriver();
PageFactory.initElements(driver, this);
}
//打开网址
public void openUrl() {
driver.get(url);
}
//关闭浏览器
public void close() {
driver.quit();
}
//输入关键字selenium并点击百度一下按扭
public void searchByKeyword() {
keyword_input.sendKeys("selenium");
search_button.click();
}
}
测试类调用方法
import org.testng.annotations.Test;
import com.suning.encapsulation.BaiduSeparatePage;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class BaiduSeparatePageTest {
@Test
public void f() {
//实例化页面对象模型
BaiduSeparatePage hsp = new BaiduSeparatePage();
//调用方法
hsp.openUrl();
hsp.searchByKeyword();
hsp.close();
}
}