1. 程式人生 > >【selenium】常用操作的封裝

【selenium】常用操作的封裝

簡介:總結整理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,等待元素列表的出現,返回此元素列表
	 * @param driver
	 * @param className 元素的className
	 * @return 返回等待的元素
	 */
	public static List<WebElement> waitElesByClassName(String className,WebDriver driver){
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		List<WebElement> targetElementList  = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy((By.className(className))));
		return targetElementList;
	}
	
	/**
	 * 通過元素的linktext,等待元素列表的出現,返回此元素列表
	 * @param driver
	 * @param linkText 元素的linktext
	 * @return 返回等待的元素
	 */
	public static List<WebElement> waitElesByLinkText(String linkText,WebDriver driver){
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		List<WebElement> targetElementList = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy((By.linkText(linkText))));
		return targetElementList ;
	}

	/**
	 * 通過元素的xpath,等待元素列表的出現,返回此元素列表
	 * @param xpath
	 * @param driver
	 * @return
	 */
	public static List<WebElement> waitElesByXpath(String xpath,WebDriver driver){
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		List<WebElement> targetElementList = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy((By.xpath(xpath))));
		return targetElementList ;
	}
	
	/**
	 * 通過元素的linkText,等待元素的出現,並點選它
	 * @param driver
	 * @param linkText
	 */
	public static void clickByLinkText(String linkText,WebDriver driver){
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		WebElement targetElement = wait.until(ExpectedConditions.elementToBeClickable(By.linkText(linkText)));
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		targetElement.click();
	}
	
	/**
	 * 通過元素的Xpath,等待元素的出現,並點選它
	 * @param driver
	 * @param xpath
	 */
	public static void clickByXpath(String xpath,WebDriver driver) {
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		WebElement targetElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));
		targetElement.click();
	}
	
	/**
	 * 通過元素的Xpath,等待元素的出現,並點選它
	 * @param driver
	 * @param css
	 */
	public static void clickByCss(String css,WebDriver driver){
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		WebElement targetElement = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(css)));
		targetElement.click();
	}
	
	
	/**
	 * 通過元素的ID,等待元素的出現,並點選它
	 * @param driver
	 * @param Id
	 */
	public static void clickById(String Id,WebDriver driver ){
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		WebElement targetElement = wait.until(ExpectedConditions.elementToBeClickable(By.id(Id)));
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		targetElement.click();
	}
	
	/**
	 * 通過元素的ClassName,等待元素的出現,並點選它
	 * @param driver
	 * @param className
	 */
	public static void clickByClassName(String className,WebDriver driver) {
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		WebElement targetElement = wait.until(ExpectedConditions.elementToBeClickable(By.className(className)));
		targetElement.click();
	}
	
	/**
	 * 通過元素的Name,等待元素的出現,並點選它
	 * @param driver
	 * @param name
	 */
	public static void clickByName(String name,WebDriver driver) {
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		WebElement targetElement = wait.until(ExpectedConditions.elementToBeClickable(By.name(name)));
		targetElement.click();
	}

	/**
	 * 通過元素的Xpath,等待文字框的出現,並輸入
	 */
	public static void sendKeysByXpath(String xpath,String keys,WebDriver driver) {
		WebElement targetElement = waitByXpath(xpath,driver);
		targetElement.clear();
		targetElement.sendKeys(keys);
	}

	/**
	 * 指定元素,再輸入
	 * @param element
	 * @param keys
	 */
	public static void sendKeysByEle(WebElement element,String keys){
		element.clear();
		element.sendKeys(keys);
	}

	/**
	 * 通過元素的ID,等待文字框的出現,並輸入
	 */
	public static void sendKeysById(String Id,String keys,WebDriver driver) {
		WebElement targetElement = waitById(Id,driver);
		targetElement.clear();
		targetElement.sendKeys(keys);
	}

	/**
	 * 通過元素的name,等待文字框的出現,並輸入
	 */
	public static void sendKeysByName(String name,String keys,WebDriver driver) {
		WebElement targetElement = waitByName(name,driver);
		targetElement.clear();
		targetElement.sendKeys(keys);
	}

	/**
	 * 通過元素的ClassName,等待文字框的出現,並輸入
	 */
	public static void sendKeysByClassName(String className,String keys,WebDriver driver) {
		WebElement targetElement = waitByClassName(className,driver);
		targetElement.clear();
		targetElement.sendKeys(keys);
	}

	/**
	 * 通過元素的Name,等待文字框的出現,並輸入
	 */
	public static void SendKeysByName(String name,String keys,WebDriver driver){
		WebElement targetElement = waitByName(name, driver);
		targetElement.clear();
		targetElement.sendKeys(keys);
	}
}

web頁面基礎操作

  • WebBaseMethods.java
import org.openqa.selenium.*;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.*;
import static org.testng.AssertJUnit.assertTrue;

/*
 *作者:靈樞
 *時間:2018-12-21  上午11:21:36
 *描述:web頁面基礎操作
 **/
public class WebBaseMethods {

	/**
	 * 拖動元素
	 * @param element 元素
	 * @param xOffset 拖到目標的橫座標位置,xOffset為正數時向右移動,為負數時向左移動
	 * @param yOffset 拖到目標的縱座標位置
	 * @param driver
	 */
	public static void dragAndDropBy(WebElement element,int xOffset,int yOffset,WebDriver driver){
		Actions actions = new Actions(driver);
		actions.dragAndDropBy(element,xOffset,yOffset).build().perform();
	}

	/**
	 * 拖動滾動條到目標元素的位置
	 * @param driver
	 */
	public static void scrollIntoView(WebElement target,WebDriver driver){
		((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();",target);
	}

	/**
	 * 切換視窗
	 * @param driver
	 * @param element
	 */
	public static void switchToWindow(WebDriver driver,WebElement element){
		String currentWindow = driver.getWindowHandle();
		element.click();
		WebBaseMethods.threadsleep(1000);
		Set<String> windowHandles = driver.getWindowHandles();
		//切換視窗
		for (String windowHandle:windowHandles){
			if(!windowHandle.equals(currentWindow)){
				driver.switchTo().window(windowHandle);
			}
		}
	}

    /**
     * 通過frame的ID切換iframe
     * @param
     */
	public static void switchToFrameById(WebDriver driver,String id){
		WebElement frame = driver.findElement(By.id(id));
    	driver.switchTo().frame(frame);
    }
	
	/**
	 * 切換iframe
	 * @param
	 */
	public static void switchToFrameByEle(WebDriver driver,WebElement iframe){
		driver.switchTo().frame(iframe);
	}
	
	/**
	 * 接收alert
	 * @param
	 */
	public static void acceptAlert(WebDriver driver){
		try {
			Alert alert = driver.switchTo().alert(); //接收alert
			alert.accept();
		} catch (Exception e) {
		}
	}

	/**
	 * 等待alert出現
	 * @param alertName
	 * @param driver
	 * @return
	 */
	public static Alert waitForAlert(String alertName,WebDriver driver){
		WebDriverWait wait = new WebDriverWait(driver, 10);
		Alert targetAlert = null;
		try{
			targetAlert = wait.until(ExpectedConditions.alertIsPresent());
		}catch(Exception e){
			assertTrue("沒有找到目標元素--"+alertName,false);
		}
		return targetAlert;
	}
	
	/**
	 * 用javaScript執行點選事件
	 * @param
	 */
	public static void clickByJS(WebElement ele,WebDriver driver){
		JavascriptExecutor js = (JavascriptExecutor)driver;
		js.executeScript("arguments[0].click();", ele);
	}
	
    /**
	*切換到指定名稱的視窗
	*@param
	*@return
	 */
    public static void switchToWindowHandle(String windowTitleName,WebDriver driver){
    	Set<String> handles = driver.getWindowHandles();
    	List<String> it = new ArrayList<String>(handles);
    	Iterator<String> iterator = handles.iterator();
    	String currentHandle=null;
    	try{
    		currentHandle=driver.getWindowHandle();
    	}
    	catch(NoSuchWindowException e){
    		driver.switchTo().window(it.get(0));
    	}
    	while (iterator.hasNext()) {
    		String h = (String) iterator.next();
    		String currentTitle=driver.getTitle();
    		if (currentTitle.contains(windowTitleName)){
    			break;
    		}
	    		if (h != currentHandle) {
	    		 if (driver.switchTo().window(h).getTitle().contains(windowTitleName)) {
	    			driver.switchTo().window(h);
		    		System.out.println("switch to "+driver.getTitle()+" news page successfully");
		    		break;
	    		}
	    	}
    	}
    }

	/**
	 * 滑鼠懸停
	 * @param ele 元素
	 * @param time 懸停時間
	 * @param driver
	 */
	public static void mouthHover(WebElement ele,int time,WebDriver driver){
		Actions builder = new Actions(driver);
		Actions hoverOverRgeistrar = builder.moveToElement(ele);
		hoverOverRgeistrar.perform();
		WebBaseMethods.threadsleep(time);
    }
    
    /**
	*滑鼠點選並懸停
	 */
    public static void clickAndHold(WebElement ele,WebDriver driver){
		Actions builder = new Actions(driver);
		Actions hoverOverRgeistrar = builder.clickAndHold(ele);
		hoverOverRgeistrar.perform();
    }
    
    /**
	*雙擊
	 */
    public static void doubleClick(WebElement ele,WebDriver driver){
		Actions builder = new Actions(driver);
		Actions hoverOverRgeistrar = builder.doubleClick(ele);
		hoverOverRgeistrar.perform();
    }


	/**
	 * 執行緒等待
	 * @param timeout 單位:毫秒
	 */
	public static void threadsleep(int timeout){
		try {
			Thread.sleep(timeout);
    	   } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
    	   }
	}
	
	/**
	 * 判斷元素是否存在
	 * @param driver
	 * @param ele 等待的元素
	 * @return boolean 是否存在
	 */
	public static boolean isElementExsit(WebElement ele,WebDriver driver) {
        boolean flag ;
        try {  
        	WebDriverWait wait = new WebDriverWait(driver,20);
			WebElement element = wait.until(ExpectedConditions.visibilityOf(ele));
			flag = element.isDisplayed();
        } catch (Exception e) {  
        	flag = false;
            System.out.println("Element:" + ele.toString()  
                    + " is not exsit!");  
        }  
        return flag;  
    } 
	
	/**
	 * 判斷元素是否存在
	 * @param driver
	 * @param locator 如:By.id("")
	 * @return boolean 是否存在
	 */
	public static boolean isElementExsitBy(By locator,WebDriver driver) {
        boolean flag = false;  
        try {
			WebDriverWait wait = new WebDriverWait(driver, 20);
			WebElement	element = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
            flag=element.isDisplayed();
        } catch (NoSuchElementException e) {
            System.out.println("Element:" + locator.toString()  
                    + " is not exsit!");  
        }  
        return flag;  
    }  
	
	/**
	 * 等待元素可見
	 * @param driver
	 * @param ele
	 * @param waitTime
	 */
	public static void waitForElementVisible(WebDriver driver,WebElement ele,int waitTime){
    	WebDriverWait wait = new WebDriverWait(driver,waitTime);
	 	wait.until(ExpectedConditions.visibilityOf(ele));   
    }

	/**
	 * 等待元素可點選
	 * @param driver
	 * @param ele
	 * @param waitTime
	 */
	public static void waitForWebElementToBeClickable(WebDriver driver,WebElement ele,int waitTime){
    	WebDriverWait wait = new WebDriverWait(driver,waitTime);
    	wait.until(ExpectedConditions.visibilityOf(ele));  
	 	wait.until(ExpectedConditions.elementToBeClickable(ele));  
    }
}