简介:总结整理selenium常用操作的封装,包括对元素操作的封装和页面基础操作封装,方便在写自动化用例时直接调用。
元素操作的封装
- OperateElement.java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
/*
*作者:灵枢
*时间:2018-11-22 下午4:45:15
*描述:元素的基本操作
**/
public class OperateElement {
private static int timeOutInSeconds = 20;
/**
* 通过元素的Xpath,等待元素的出现,返回此元素
* @param driver
* @return 返回等待的元素
*/
public static WebElement waitByXpath(String xpath,WebDriver driver){
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
//presenceOfElementLocated:显示等待元素在页面中存在,不用等页面全部加载完
WebElement targetElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
return targetElement;
}
/**
* 通过元素的name,等待元素的出现,返回此元素
* @param driver
* @param name 元素的name
* @return 返回等待的元素
*/
public static WebElement waitByName(String name,WebDriver driver){
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
WebElement targetElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.name(name)));
return targetElement;
}
/**
* 通过元素的id,等待元素的出现,返回此元素
* @param driver
* @param id 元素的id
* @return 返回等待的元素
*/
public static WebElement waitById(String id,WebDriver driver){
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
WebElement targetElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.id(id)));
return targetElement;
}
/**
* 通过元素的linkText,等待元素的出现,返回此元素
* @param driver
* @param linkText 元素的linkText
* @return 返回等待的元素
*/
public static WebElement waitByLinkText(String linkText,WebDriver driver){
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
WebElement targetElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText(linkText)));
return targetElement;
}
/**
* 通过元素的className,等待元素的出现,返回此元素
* @param driver
* @param className 元素的className
* @return 返回等待的元素
*/
public static WebElement waitByClassName(String className,WebDriver driver){
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
WebElement targetElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.className(className)));
return targetElement;
}
/**
* 通过元素的Css,等待元素的出现,返回此元素
* @param driver
* @return 返回等待的元素
*/
public static WebElement waitByCss(String css,WebDriver driver){
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
WebElement targetElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(css)));
return targetElement;
}
/**
* 通过元素的className,等待元素列表的出现,返回此元素列表
*