1. 程式人生 > 實用技巧 >20200814_App元素定位&滑動操作

20200814_App元素定位&滑動操作

1、APP元素定位

  1. ID定位
  2. text定位
  3. className定位-這種方式一般得到的會是多個元素
  4. Xpath定位
  5. accessibility id定位-在UIAutomatorViewer並沒有此屬性,對應是content-desc屬性
  6. 座標定位 -- 只能執行點選操作-xpath支援單引號
    • 設定座標操作:選擇設定中關於手機->連續點選五次版本號->進入開發者選項->指標位置進行勾選
    • 座標定位受裝置螢幕尺寸/解析度/DPI影響,萬不得已不要使用此種方式
//1、ID
//找到我的檸檬元素並且點選
androidDriver.findElement(MobileBy.id("com.lemon.lemonban:id/navigation_my")).clic
k();

//2、text--雙引號要轉義下 androidDriver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().text(\"全 程班\")"); // 3、className androidDriver.findElement(MobileBy.className("android.widget.LinearLayout")); //4 、Xpath androidDriver.findElement(MobileBy.xpath("//android.widget.TextView[@text='全程 班']")); 裡頭有單引號,是因為xpath支援單引號
//5、AccessibilityId androidDriver.findElement(MobileBy.AccessibilityId("題庫"));

2、等待-toast元素如何定位(不會獲得焦點,無法被點選)-一種簡易的訊息提示框

獲取方式:

  • 隱式等待
    androidDriver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
    androidDriver.findElement(MobileBy.xpath("//*[contains(@text, 'tips')]"));
  • 顯示等待-等待條件只能夠去用等待元素存在這一個
    WebElement webElement = webDriverWait.until(ExpectedConditions.
    presenceOfElementLocated(MobileBy.xpath(
    "//*[contains(@text,'賬號信 息')]"))); System.out.println(webElement.getText());

3、滑動操作-兩個位置從一個移動到另外一個

    //向左滑動方法
    public void swipeleft(int time){
        //獲取螢幕寬和高
        int width = androidDriver.manage().window().getSize().getWidth();
        int height = androidDriver.manage().window().getSize().getHeight();
        TouchAction touchAction = new TouchAction(androidDriver);
        PointOption pointOption1 = PointOption.point(width*3/4,height/2);
        PointOption pointOption2 = PointOption.point(width/4,height/2);

        Duration duration = Duration.ofMillis(time);
        WaitOptions waitOptions = WaitOptions.waitOptions(duration);
        touchAction.press(pointOption1).waitAction(waitOptions).moveTo(pointOption2).release().perform();
    }
    @Test
    public void testSwipe() throws InterruptedException {
        //swipeDown();
        //連續向左滑動四次
        swipeleft(200);
        swipeleft(200);
        swipeleft(200);
        swipeleft(200);
        Thread.sleep(5000);
        androidDriver.quit();

    }