1、判断一个元素是否存在
public boolean isElementExist(By by){
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
2、查找元素
public WebElement findById(String id){
WebElement element = null;
if(this.isElementExist(By.id(id))){
element = driver.findElement(By.id(id));
}
return element;
}
3、判断元素列表是否存在
public boolean elementsExists(By by){
return (driver.findElements(by).size()>0)?true:false;
}
4、获取元素列表中指定的元素
public WebElement FindByElements(By by,int index){
WebElement element = null;
if(this.elementsExists(by)){
element = driver.findElements(by).get(index);
}
return element;
}
5、判断弹出框
public boolean isAlertPresent(){
try {
alert = driver.switchTo().alert();
return true;
} catch (NoAlertPresentException Ex) {
return false;
}
}
6、接受弹出框
public void acceptAlert(){
if(this.isAlertPresent()){
alert.accept();
}
}
7、取消弹出框
public void dimissAlert(){
if(this.isAlertPresent()){
alert.dismiss();
}
}
8、获取弹出内容
public String getAlertText(){
String text = null ;
if(this.isAlertPresent()){
text = alert.getText();
}else{
//todo:log;
}
return text;
}
切换窗口
public void switchToWindow(String windowTtitle){
Set windowHandles = driver.getWindowHandles();
for(String handler:windowHandles){
driver.switchTo().window(handler);
String title = driver.getTitle();
if(windowTtitle.equals(title)){
break;
}
}
}
切换窗口-根据frameid
public void switchToFrame(String frameId){
driver.switchTo().frame(frameId);
}
public void switchToFrame(int index){
driver.switchTo().frame(index);
}
根据元素切换窗口
public void switchToframe(WebElement element){
driver.switchTo().frame(elemenet);
}
判断是否加载有JQuery
public Boolean JQueryLoaded(){
Boolean loaded;
JavascriptExecutor js =(JavascriptExecutor)driver;
try{
loaded =(Boolean)js.executeScript("return"+"JQuery()!=null")
}catch(WebDriverException e){
loaded = false;
}
return loaded;
}
截屏
public void screenShot(WebDriver driver){
String dir_name ="screenshot";
if(!(new File(dir_name).isDirectory)){
new File(dir_name).mkdir();
}
SimpleDateFormat sdf = new SimpleDataFormat("yyyyMMdd-HHmmss");
String time = sdf.format(new Date());
try{
File source_file=((TakesScreenshot)driver.getScreenshotAs(OutputType.FILE));//执行截屏
FileUtils.copyFile(source_file,new File(dir_name+File.separator+time+".png"));
}catch(IOException e){
e.printStackTrace();
}
}
//获取键盘
public Keyboard getKeyboard(){
return ((HasInputDevices)driver).getKeyboard();
}
//模拟crtrl+F5
public void refreshWithCtrlF5(){
getKeyboard().sendKeys(keys.CONTROL,Keys.F5);
}