转载自51testing
简单封装API方法
import
java.util.List;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class WebDiverBaseLib {
public static WebDriver driver;
/**
* 判断页面元素是否存在
*
* @param by
* @return boolean
*/
public boolean isElementExist(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
// TODO: handle exception
return false;
}
}
/**
* 根据id定位页面元素
*
* @param id
* @return element
*/
public WebElement findByID(String id) {
WebElement element = null;
if (this.isElementExist(By.id(id))) {
element = driver.findElement(By.id(id));
}
return element;
}
/**
* 根据name定位页面元素
*
* @param name
* @return element
*/
public WebElement findByName(String name) {
WebElement element = null;
if (this.isElementExist(By.name(name))) {
element = driver.findElement(By.name(name));
}
return element;
}
/**
* 根据class定位页面元素
*
* @param ClassName
* @return element
*/
public WebElement findByClass(String ClassName) {
WebElement element = null;
if (this.isElementExist(By.name(ClassName))) {
element = driver.findElement(By.name(ClassName));
}
return element;
}
/**
* 根据LinkText定位页面元素
*
* @param LinkText
* @return
*/
public WebElement findByLinkText(String LinkText) {
WebElement element = null;
if (this.isElementExist(By.name(LinkText))) {
element = driver.findElement(By.name(LinkText));
}
return element;
}
/**
* 根据元素index获取具体元素位置
*
* @param by
* @param index
* @return element
*/
public WebElement FindByElements(By by, int index) {
WebElement element = null;
if (this.isElementExist(by)) {
element = driver.findElements(by).get(index);
}
return element;
}
/**
* 查找列表元素是否存在
*
* @param by
* @return boolean
*/
public boolean elementsExists(By by) {
return (driver.findElements(by).size()) > 0 ? true : false;
}
/**
* 窗口切换
*
* @param windowTitile
*/
public void switchTowindow(String windowTitile) {
Set<String> windowHandles = driver.getWindowHandles();
for (String handler : windowHandles) {
driver.switchTo().window(handler);
String title = driver.getTitle();
if (windowTitile.equals(title)) {
break;
}
}
}
/**
* 根据option下拉列表名称找找 查找下拉属性元素位置点击
*
* @param id
* @return Element
*/
public WebElement findSelectById(String Text) {
WebElement element = null;
List<WebElement> ptions = driver.findElements(By.name(Text));
for (int i = 0; i < options.size(); i++) {
if (options.get(i).getText().equals(Text)) {
options.get(i).click();
}
}
return element;
}
}