selenium教程——常用方法
前面我们已经学习了定位元素, 定位只是第一步, 定位之后需要对这个元素进行操作, 或单击(按钮) 或 输入(输入框) , 下面就来认识这些最常用的方法。
import java.io.File;
import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchWindowException; import org.openqa.selenium.OutputType; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.os.WindowsUtils; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; public class SeleniumUtil { private static WebDriver driver; public Logger logger=Logger.getLogger(SeleniumUtil.class); public SeleniumUtil(WebDriver driver) { SeleniumUtil.driver = driver; } //获取网页title public String getTitle(){ return driver.getTitle(); } //强制等待 public static void sleepTime(int num){ try { Thread.sleep(num); } catch (InterruptedException e) { e.printStackTrace(); } } //获取当前网页的url public String getCurrentUrl(){ return driver.getCurrentUrl(); } public String PageSource(){ return driver.getPageSource(); } //浏览器最大化 public void windowMaxSize(){ driver.manage().window().maximize(); } //关闭当前页面 public void closePage(){ driver.close(); } //关闭浏览器 public void closeBroser(){ driver.quit(); } /** * * @Title: switchFrame * @Description: TODO(跳转到frame,以下通过重载实现不同方式跳转到frame) */ public void switchFrame(int num){ driver.switchTo().frame(num); logger.info("根据索引进入frame"); } public void switchFrame(String FrameName){ driver.switchTo().frame(FrameName); logger.info("根据name进入frame"); } public void switchFrame(WebElement webElement){ driver.switchTo().frame(webElement); logger.info("根据frame的具体元素进入frame"); } public void initFrame(){ driver.switchTo().defaultContent(); logger.info("返回值frame的初始位置"); } public void BrowserBack(){ driver.navigate().back(); logger.info("点击浏览器返回按钮"); } public void BrowserForWard(){ driver.navigate().forward(); logger.info("点击浏览器前进按钮"); } public void sendKey(WebElement we, String key){ we.clear(); we.sendKeys(key); } public void doubleClick(WebElement we){ Actions action=new Actions(driver); action.doubleClick(we).build().perform(); logger.info("对元素"+we+"进行双击操作"); } public void selectByIndex(WebElement element,int num){ Select select=new Select(element); select.selectByIndex(num); logger.info("选择下拉框第"+(num+1)+"个选项"); } public void selectByValue(WebElement element,String value){ Select select=new Select(element); select.selectByValue(value); logger.info("选择下拉框"+value+"选项"); } public void selectByText(WebElement element,String content){ Select select=new Select(element); select.selectByVisibleText(content);; logger.info("选择下拉框"+content+"选项"); } public void checkSelectText(WebElement we,List<String> expect_option){ Select select =new Select(we); List<String> actual_option=new ArrayList<>(); for (WebElement option : select.getOptions()) { actual_option.add(option.getText()); Assert.assertEquals(expect_option.toArray(),actual_option.toArray() ); logger.info(expect_option.toArray()+"与预期结果一致"); } } public boolean is_selected(WebElement we){ try { logger.info("元素被选中"); return we.isSelected(); } catch (Exception e) { e.printStackTrace(); } return false; } public void killIeProcess(){ WindowsUtils.tryToKillByName("iexplore.exe"); logger.info("杀掉ie进程"); } public void killFireFoxProcess(){ WindowsUtils.tryToKillByName("firefox.exe"); logger.info("杀掉火狐进程"); } public void killChromeProcess(){ WindowsUtils.tryToKillByName("chrome.exe"); logger.info("杀掉chrome进程"); } public void killProcess(String name){ WindowsUtils.tryToKillByName(name); logger.info("杀掉"+name+"进程"); } //对屏幕进行截屏 public void ScreenInCurrentWindow(File outFile){ File scrFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);//依赖driver try { FileUtils.copyFile(scrFile, outFile); } catch (IOException e) { e.printStackTrace(); } } //拖曳某个元素,不常用 public void dragPageElement(WebElement we,int row,int raw){ new Actions(driver).dragAndDropBy(we, row, raw).build().perform(); } //在元素上悬浮 public void hoverOnElement(WebElement we){ Actions actions=new Actions(driver); actions.moveToElement(we).perform(); logger.info("指定元素上悬浮"); } /** * * @Title: identifyPopupWindowByTitle * @Description: TODO(根据title,跳转到不同的handle,既就是不同窗口之间的切换) * @param: @param parialTitleName * @return: void */ public void identifyPopupWindowByTitle(String parialTitleName){ Set<String> handles=driver.getWindowHandles(); String titleName; for (String handle : handles) { titleName=driver.switchTo().window(handle).getTitle(); if (titleName.contains(parialTitleName)) { break; } } } //判断alert框是否存在 public boolean isAlertExist() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException ex1) { return false; } catch (NoSuchWindowException ex2) { return false; } }
//确认操作 public void alertAccept(){ Alert alert=driver.switchTo().alert(); alert.accept(); } //取消操作 public void alertDismiss(){ Alert alert=driver.switchTo().alert(); alert.dismiss(); } //alter框输入内容
public void alertPrompt(String content){ Alert alert=driver.switchTo().alert(); alert.sendKeys(content); } //使用js室滚动条下滑,col 和row 控制滑动的像素 public void scrollingByCoordinatesofApage(int col,int row){ String js="window.scrollBy("+col+","+row+")"; ((JavascriptExecutor)driver).executeScript(js); } //在指定超时时间内元素是否存在,如存在返回结果,不存在会在超时后返回结果。单位是秒 public static boolean isElementExist(By by,int timeout){ try { new WebDriverWait(driver, timeout).until(ExpectedConditions.presenceOfElementLocated(by)); return true; } catch (Exception e) { return false; } } public static boolean isElementPresent(By by){ try{ driver.findElement(by); return true; }catch(Exception e){ return false; } }
public void jsClick(WebElement element) { try { if (element.isDisplayed() && element.isEnabled()) { ((JavascriptExecutor)driver).executeScript("arguments[0].click();",element); }else { logger.info("页面的元素无法进行单击操作"); } } catch (StaleElementReferenceException e) { logger.error("页面元素没有附加在网页中"+e.getStackTrace()); }catch (NoSuchElementException e) { logger.error("在页面中没有找到要操作的页面元素"+e.getStackTrace()); } catch (Exception e) { logger.error("无法完成单击动作"+e.getStackTrace()); } }
//对当前元素进行高亮显示 public void highlightElement(WebElement element) { JavascriptExecutor jsExecutor=(JavascriptExecutor)driver; jsExecutor.executeScript("arguments[0].setAttribute('style',arguments[1]);", element,"background:yellow;border:2px solid red"); } }
作者:风居住的街道
本文版权归作者和博客园共有,欢迎转载, 若文中有什么错误,欢迎指出。以免更多的人被误导。