appium樣例代碼

appium樣例代碼

com.appium.driver包下建立InitDriver.java類:java

package com.appium.driver; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import io.appium.java_client.AppiumDriver; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.remote.AndroidMobileCapabilityType; import io.appium.java_client.remote.MobileCapabilityType; public class InitDriver { public static AndroidDriver<AndroidElement> initDriverWebapp() throws MalformedURLException{ DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(MobileCapabilityType.DEVICE_NAME, "chinablue"); caps.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome"); caps.setCapability(MobileCapabilityType.UDID, "DU3ADH154V007404"); caps.setCapability(AndroidMobileCapabilityType.UNICODE_KEYBOARD, true); caps.setCapability(AndroidMobileCapabilityType.RESET_KEYBOARD, true); caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android"); caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "4.4.2"); URL url = new URL("http://127.0.0.1:4723/wd/hub"); AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(url,caps); return driver; } public static AndroidDriver<AndroidElement> initDriver() throws MalformedURLException{ File apk_path = new File("apps/zhihu.apk"); DesiredCapabilities caps = new DesiredCapabilities(); // 與appium服務器相關的caps caps.setCapability(MobileCapabilityType.DEVICE_NAME, "chinablue"); caps.setCapability(MobileCapabilityType.APP, apk_path.getAbsolutePath()); // 手機網頁測試 // caps.setCapability(MobileCapabilityType.BROWSER_NAME, "chinablue"); // caps.setCapability(MobileCapabilityType.UDID, "127.0.0.1:62001"); // 服務端等待客戶端發送腳本命令時間 caps.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 600); // 與android相關的caps // 默認就是false caps.setCapability(AndroidMobileCapabilityType.NO_SIGN, false); // 支持輸入時使用中文 caps.setCapability(AndroidMobileCapabilityType.UNICODE_KEYBOARD, true); caps.setCapability(AndroidMobileCapabilityType.RESET_KEYBOARD, true); // 判斷鏈接的Android設備應答超時,默認5s caps.setCapability(AndroidMobileCapabilityType.DEVICE_READY_TIMEOUT, 10); // 若是apk的起始activity和apk開機後穩定顯示的activity不是一個時,須要指定activity // caps.setCapability(AndroidMobileCapabilityType.APP_WAIT_ACTIVITY, ""); // 啓動手機已有apk。此時指定apk包名和起始activity便可 // caps.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, ""); // caps.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ""); AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>( new URL("http://127.0.0.1:4723/wd/hub"),caps); return driver; } public static AndroidDriver<AndroidElement> initDriverInstalledApp(String appPackage,String appActivity ) throws MalformedURLException{ File apk_path = new File("apps/zhihu.apk"); DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(MobileCapabilityType.DEVICE_NAME, "chinablue"); caps.setCapability(MobileCapabilityType.UDID, "127.0.0.1:62001"); caps.setCapability(AndroidMobileCapabilityType.UNICODE_KEYBOARD, true); caps.setCapability(AndroidMobileCapabilityType.RESET_KEYBOARD, true); caps.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, appPackage); caps.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, appActivity); AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>( new URL("http://127.0.0.1:4723/wd/hub"),caps); return driver; } } 

com.appium.driver包下建立AppiumUtils.java類:android

package com.appium.driver; import java.io.File; import java.io.IOException; import java.time.Duration; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.Point; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.android.AndroidKeyCode; public class AppiumUtils { /** * 獲取輸入框的text文本 將光標置於輸入框的最後 根據文本長度循環調用物理鍵盤刪除掃除,逐個字符進行刪除 * * @throws InterruptedException * * 注意:此方法對於密碼輸入框此方法無效。因密碼輸入框的特性是密碼值不會寫入到text屬性中 * 思路:可根據密碼長度強制刪除密碼最長長度次 */ public static void clearText(AndroidDriver<AndroidElement> driver, AndroidElement element) throws InterruptedException { element.click(); String text = element.getText(); // 將光標置於文本最後 driver.pressKeyCode(AndroidKeyCode.KEYCODE_MOVE_END); for (int i = 0; i < text.length(); i++) { driver.pressKeyCode(AndroidKeyCode.BACKSPACE); Thread.sleep(200); } } /** * @param driver * @param element * @param passwdMaxLength * @throws InterruptedException */ public static void clearWithPwd(AndroidDriver<AndroidElement> driver, AndroidElement element, int passwdMaxLength) throws InterruptedException { element.click(); driver.pressKeyCode(AndroidKeyCode.KEYCODE_MOVE_END); for (int i = 0; i < passwdMaxLength; i++) { driver.pressKeyCode(AndroidKeyCode.BACKSPACE); Thread.sleep(200); } } public static boolean isElementExist(AndroidDriver<AndroidElement> driver, By by) { try { driver.findElement(by); return true; } catch (Exception e) { // TODO: handle exception return false; } } // public static void swipeToUp(AndroidDriver<AndroidElement> driver,int during,int num){ // int width = driver.manage().window().getSize().width; // int height = driver.manage().window().getSize().height; // for (int i = 0; i < num; i++) { // driver.swipe(width/2, height*3/4, width/2, height*1/4, during); // // } // } public static void swipeToLeft(AndroidDriver<AndroidElement> driver,int during){ int width = driver.manage().window().getSize().width; int height = driver.manage().window().getSize().height; TouchAction leftSwipe = new TouchAction(driver); leftSwipe.press(width/4, height/2).waitAction(Duration.ofMillis(during)).moveTo(width*3/4, height/2).release(); leftSwipe.perform(); } public static void swipeToUp(AndroidDriver<AndroidElement> driver, int during) { int width = driver.manage().window().getSize().width; int height = driver.manage().window().getSize().height; TouchAction upSwipe = new TouchAction(driver); upSwipe.press(width/2, height/4).waitAction(Duration.ofMillis(during)).moveTo(width/2, height*3/4).release(); upSwipe.perform(); } public static void swipeToDown(AndroidDriver<AndroidElement> driver, int during) { int width = driver.manage().window().getSize().width; int height = driver.manage().window().getSize().height; TouchAction downSwipe = new TouchAction(driver); downSwipe.press(width/2, height*3/4).waitAction(Duration.ofMillis(during)).moveTo(width/2, height/4).release(); downSwipe.perform(); } public static void swipeToRight(AndroidDriver<AndroidElement> driver, int during) { int width = driver.manage().window().getSize().width; int height = driver.manage().window().getSize().height; TouchAction rightSwipe = new TouchAction(driver); rightSwipe.press(width*3/4, height/2).waitAction(Duration.ofMillis(during)).moveTo(width/4, height/2).release(); rightSwipe.perform(); } enum SwipeDirection{ up,down,right,left; public static SwipeDirection getSwipeDirection(String direction){ return valueOf(direction); } } public static void swipe(AndroidDriver<AndroidElement> driver, int during, String direction){ switch (SwipeDirection.getSwipeDirection(direction.toLowerCase())) { case up: swipeToUp(driver, during); break; case down: swipeToDown(driver, during); break; case right: swipeToRight(driver, during); break; case left: swipeToLeft(driver, during); break; default: System.out.println("方向參數只能是 up/down/right/left"); break; } } /** * @param driver * @param by * @return * 功能:定位元素而且獲取元素結束點座標 */ public static Point getElementCoor(AndroidDriver<AndroidElement> driver,By by){ AndroidElement element = driver.findElement(by); // // 獲取元素起始點座標 // int startx = element.getLocation().getX(); // int starty = element.getLocation().getY(); // // 獲取元素的寬高 // int width = element.getSize().getWidth(); // int height = element.getSize().getHeight(); // // 計算出元素結束點座標 // int endx = startx + width; // int endy = starty + height; return getElementCoor(element); } /** * @param driver * @return:返回一個Point對象 */ public static Point getElementCoor(AndroidElement element){ // 獲取元素起始點座標 int startx = element.getLocation().getX(); int starty = element.getLocation().getY(); // 獲取元素的寬高 int width = element.getSize().getWidth(); int height = element.getSize().getHeight(); // 計算出元素結束點座標 int endx = startx + width; int endy = starty + height; return new Point(endx,endy); } /** * 截圖方法 * @param driver * @param filename * @throws IOException */ public void getScreenShotcut(AndroidDriver<AndroidElement> driver,String filename) throws IOException{ File file = driver.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(file, new File("images\\"+filename+".png")); } } 

樣例代碼:apache

package com.appium.zhihu; import java.io.File; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.ScreenOrientation; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.mobile.NetworkConnection; import org.openqa.selenium.mobile.NetworkConnection.ConnectionType; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.appium.driver.AppiumUtils; import com.appium.driver.InitDriver; import com.sun.javafx.scene.traversal.Direction; import io.appium.java_client.AppiumDriver; import io.appium.java_client.TouchAction; import io.appium.java_client.android.Activity; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.android.AndroidKeyCode; import io.appium.java_client.functions.ExpectedCondition; import net.bytebuddy.asm.Advice.This; public class ZhihuLogin { public static AndroidDriver<AndroidElement> driver; public ZhihuLogin(AndroidDriver<AndroidElement> driver){ this.driver = driver; } public void login(){ // driver.findElement(By.xpath("//*[@text='未登陸']")).click(); driver.findElementByAndroidUIAutomator("new UiSelector().text(\"未登陸\")").click(); delayTime(200); // driver.findElement(By.xpath("//android.support.v7.widget.LinearLayoutCompat/android.support.v7.widget.LinearLayoutCompat/android.widget.ImageView[1]")).click(); driver.findElement(By.xpath("//*[@resource-id='com.zhihu.android:id/login_phone']")).click(); delayTime(200); driver.findElement(By.xpath("//*[@text='密碼登陸']")).click(); delayTime(200); driver.findElement(By.xpath("//*[@text='輸入手機號或郵箱']")).sendKeys("15099947428"); delayTime(200); driver.findElement(By.xpath("//android.support.v7.widget.LinearLayoutCompat/android.widget.EditText[2]")).sendKeys("chinablue2018"); delayTime(200); driver.findElement(By.xpath("//*[@text='登陸']")).click(); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 拿到界面上的全部資源 if(driver.getPageSource().contains("已購")){ System.out.println("登錄成功"); }else{ System.out.println("登錄失敗"); } } public static void logout(){ clickMenu(5); if(AppiumUtils.isElementExist(driver, By.name("設置"))){ driver.findElement(By.name("設置")).click(); }else{ AppiumUtils.swipe(driver, 500, "down"); driver.findElement(By.name("設置")).click(); } while(true){ if(AppiumUtils.isElementExist(driver, By.id("com.zhihu.android:id/func_text"))){ driver.findElement(By.id("com.zhihu.android:id/func_text")).click(); driver.findElement(By.name("肯定")).click(); break; }else{ AppiumUtils.swipe(driver, 500, "down"); } } } /** * * @param order */ public static void clickMenu(int order){ //android.widget.LinearLayout/*[@class='android.support.v7.widget.LinearLayoutCompat'][1] driver.findElement(By.xpath("//android.widget.HorizontalScrollView/android.widget.LinearLayout/descendant::android.support.v7.widget.LinearLayoutCompat["+order+"]")).click(); } public static void delayTime(long timeout){ try { Thread.sleep(timeout); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void attention(){ List<AndroidElement> titles = driver.findElements(By.xpath("//*[@resource-id='com.zhihu.android:id/title']")); System.out.println("當前頁面文章標題數爲:"+titles.size()); for(AndroidElement title: titles){ title.click(); delayTime(5000); driver.pressKeyCode(4); } } public void loginByUiautomator(){ // 此方法只能用於Android原生APP driver.findElementByAndroidUIAutomator("new UiSelector().text(\"未登陸\")").clear(); } public void nightMode(){ clickMenu(5); AndroidElement nightMode = driver.findElement(By.id("com.zhihu.android:id/night_mode_switch")); String status = nightMode.getAttribute("checked"); System.out.println(status); AppiumUtils.swipe(driver, 500, "down"); nightMode.click(); status = nightMode.getAttribute("checked"); if(status.equals("true")){ System.out.println("夜間模式打開"); }else{ System.out.println("夜間模式關閉"); } } /** * 獲取元素的起始點座標、結束點座標、中心點座標 */ public void getCoor(){ // int end_x = AppiumUtils.getElementCoor(driver, By.id("")).getX(); // int end_y = AppiumUtils.getElementCoor(driver, By.id("")).getY(); // 上述寫法定位元素次數有所增長,故須要優化 Point p = AppiumUtils.getElementCoor(driver, By.id("")); int endx = p.getX(); int endy = p.getY(); } public static void tap(){ AndroidElement element = driver.findElement(By.id("")); element.replaceValue(""); // element.tap(); } /** * 打開另外一個應用 快手app */ public void startKuaiShou(){ Activity activity = new Activity("com.smile.gifmaker", "com.yxcorp.gifshow.HomeActivity"); // activity.setAppWaitPackage("com.smile.gifmaker"); // activity.setAppWaitActivity("com.yxcorp.gifshow.HomeActivity"); // activity.setStopApp(false); driver.startActivity(activity); delayTime(5000); // 獲取當前activity,能夠判斷界面跳轉(前提是跳轉後界面的activity發生了變化) String currentActivity = driver.currentActivity(); System.out.println(currentActivity); } /** * 獲取網絡狀態:getNetworkConnection().toString();或getNetworkConnection().value(); * 設置網絡狀態:setNetworkConnection() */ public void networkGetAndSet(){ // new NetworkConnection() { // // public ConnectionType setNetworkConnection(ConnectionType type) { // // TODO Auto-generated method stub // return null; // } // // public ConnectionType getNetworkConnection() { // // TODO Auto-generated method stub // return null; // } // }; NetworkConnection mobileDriver = (NetworkConnection)driver; String networkInfo = mobileDriver.getNetworkConnection().toString(); System.out.println(networkInfo); } public static void getOrientation(){ ScreenOrientation orientation = driver.getOrientation(); // 獲取屏幕方向信息 System.out.println(orientation.value()); delayTime(5000); // 設置屏幕方向,若是app自己不支持橫豎屏切換,那麼會報錯 driver.rotate(ScreenOrientation.LANDSCAPE); System.out.println(orientation.value()); } /** * qq應該 * com.tencent.mobileqq * com.tencent.mobileqq.activity.SplashActivity */ public void appInstallandRemove(){ if(driver.isAppInstalled("com.tencent.mobileqq")){ driver.removeApp("com.tencent.mobileqq"); } driver.installApp("D:\\eclipse\\workspace0122\\appiumtest\\apps\\qq.apk"); System.out.println(driver.isAppInstalled("com.tencent.mobileqq")); } /** * 顯示等待的兩個使用場景 * 場景1:等待某個元素出現 * 場景2:等待屬性值出現 */ public void waitUtilElement(){ // 場景1:等待某個元素在30s內出現,不出現就拋出異常 WebDriverWait wait = new WebDriverWait(driver, 30); AndroidElement element = (AndroidElement) wait.until( ExpectedConditions.presenceOfElementLocated(By.id(""))); // 場景2:自定義顯示等待 getText WebDriverWait wait1 = new WebDriverWait(driver, 60); wait1.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver arg0) { // TODO Auto-generated method stub return driver.findElement( By.id("")).getText().contains("註冊或登錄"); } }); // 場景3:自定義顯示等待 getAttribute WebDriverWait wait2 = new WebDriverWait(driver, 60); wait2.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver arg0) { // TODO Auto-generated method stub return driver.findElement( By.id("")).getAttribute("checked").equals("true"); } }); // 場景4:自定義顯示等待 getAttribute 判斷元素是否被置灰 WebDriverWait wait3 = new WebDriverWait(driver, 60); wait3.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver arg0) { // TODO Auto-generated method stub return driver.findElement( By.id("")).getAttribute("enabled").equals("false"); } }); } /** * 若是手機鎖屏,對屏幕進行解鎖 */ public void lockToUnlock(){ if(driver.isLocked()){ driver.unlockDevice(); } // 長按某個鍵 driver.longPressKeyCode(3); } public void touchaction(){ AndroidElement element = driver.findElement(By.id("")); TouchAction touch = new TouchAction(driver); // 長按元素 touch.longPress(element).release().perform(); // 長按某個座標點 touch.longPress(300, 500).release().perform(); // 在元素的某一個點上長按 touch.longPress(element, 20, 20).release().perform(); touch.press(element).release().perform(); touch.press(300, 500).release().perform(); //實現拖拽操做 實現手勢解鎖 } public void changeLanguageHit(){ driver.pressKeyCode(AndroidKeyCode.HOME); driver.findElement(By.name("設置")).click(); AppiumUtils.isElementExist(driver, By.xpath("")); } /** * 1. 經過id定位當前屏幕的全部設置,而且獲取這個設置的文本存入到list。若是這個list大小小於15,那就向上滑動 * 2. 再次獲取當前屏幕的全部設置,而且將全部設置文本存入list,而且判重。再次判斷list大小是否大於15,若是大於,直接list.get(索引值).click()完成點擊 * */ public void helpClick(){ driver.pressKeyCode(AndroidKeyCode.HOME); driver.findElement(By.name("設置")).click(); List<String> settingTexts = new ArrayList<String>(); List<AndroidElement> settings = new ArrayList<AndroidElement>(); while(true){ List<AndroidElement> titles = driver.findElements(By.id("android:id/title")); for(AndroidElement title:titles){ String text = title.getText(); if(!settingTexts.contains(text)){ settingTexts.add(text); settings.add(title); } } System.out.println("*********"); System.out.println(settingTexts.size()); System.out.println("*********"); if(settingTexts.size()>33){ System.out.println("--------------"); for(String a:settingTexts){ System.out.println(a); } System.out.println("--------------"); settings.get(30).click(); break; }else{ AppiumUtils.swipe(driver, 1000, "down"); } delayTime(3000); } } /** * 點擊倒數第七個 * 先滑動到底部,獲取最後一屏的全部title,而後點擊倒數第7個 * 如何判斷滑動到最後一屏? * 答:每次滑動先後的界面是否一致,如何一致則表示滑動到底部了, * 其中每一個設置的文本做爲判斷滑動屏幕是否同樣的依據 */ public void settingInputWayClick(){ driver.pressKeyCode(AndroidKeyCode.HOME); driver.findElement(By.xpath("//*[@resource-id='com.huawei.android.launcher:id/hotseat']/android.view.View/android.view.View/android.widget.TextView[4]")).click(); ArrayList<String> oldTexts = new ArrayList<String>(); ArrayList<String> newTexts = new ArrayList<String>(); // ArrayList<AndroidElement> androidelement = new ArrayList<AndroidElement>(); List<AndroidElement> titles = driver.findElements(By.id("android:id/title")); for(AndroidElement title:titles){ String text = title.getText(); oldTexts.add(text); } AppiumUtils.swipe(driver, 500, "down"); for(AndroidElement title:titles){ String text = title.getText(); newTexts.add(text); } } /** * 拖拽操做:知乎app拖拽到快手app的位置 */ public void drag(){ driver.pressKeyCode(AndroidKeyCode.HOME); TouchAction touch = new TouchAction(driver); AndroidElement zhihu = driver.findElement(By.name("知乎")); AndroidElement contact = driver.findElement(By.name("快手")); touch.longPress(zhihu).moveTo(contact).release().perform(); } public void shoushisuo(){ driver.pressKeyCode(AndroidKeyCode.HOME); driver.findElement(By.name("設置")).click();; driver.findElement(By.name("安全")).click();; driver.findElement(By.name("屏幕鎖定")).click();; driver.findElement(By.name("圖案")).click(); AndroidElement element = driver.findElement(By.id("com.android.settings:id/lockPattern")); Point location = element.getLocation(); int startx = location.getX(); int starty = location.getY(); Dimension size = element.getSize(); int height = size.getHeight(); int width = size.getWidth(); // 將9個點加入到集合中 // 繪製圖案、注意絕對座標和相對座標. movoTo(1,1) TouchAction touch = new TouchAction(driver); touch.press(300,500).moveTo(20,30).moveTo(100, 20).release().perform(); } public static void main(String[] args) { AndroidDriver<AndroidElement> driver = null; try { driver = InitDriver.initDriver(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } ZhihuLogin zhihu = new ZhihuLogin(driver); // 此後全部的find查找元素 隱式等待時間都是10s driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); delayTime(15000); zhihu.login(); // zhihu.settingInputWayClick(); // zhihu.shoushisuo(); // delayTime(5000); // zhihu.appInstallandRemove(); // zhihu.getOrientation(); // zhihu.delayTime(6000); // zhihu.nightMode(); // for (int i = 0; i < 3; i++) { // AppiumUtils.swipe(driver, 300,"down"); // zhihu.delayTime(2000); // } // zhihu.clickMenu(1); // zhihu.delayTime(6000); // logout(); // for (int i = 0; i < 3; i++) { // AppiumUtils.swipe(driver, 300,"down"); // zhihu.delayTime(2000); // } // // AppiumUtils.swipe(driver, 300,"left"); // for (int i = 0; i < 3; i++) { // AppiumUtils.swipe(driver, 300,"down"); // zhihu.delayTime(2000); // } // // AppiumUtils.swipe(driver, 300,"right"); // for (int i = 0; i < 3; i++) { // AppiumUtils.swipe(driver, 300,"down"); // zhihu.delayTime(2000); // } // while(true){ // AppiumUtils.swipeToDown(driver, 100); // zhihu.delayTime(100); // } // // for (int i = 0; i < 8; i++) { // AppiumUtils.swipeToUp(driver, 200); // zhihu.delayTime(3000); // } // zhihu.attention(); driver.quit(); } } 
相關文章
相關標籤/搜索