如何使用循环滑动直到在appium中找到元素

时间:2020-10-18 17:11:27

标签: java android appium appium-android

我可以滑动直到找到元素,但是随后出现NoSuchElementException。

我写了以下代码。

int startX=(int) (dimension.width*0.5);
        int startY=(int) (dimension.height*0.8);

        int endX=(int) (dimension.width*0.2);
        int endY=(int) (dimension.width*0.2);

        TouchAction touch=new TouchAction(driver);
        boolean b=false;
        while (true) {
            touch.press(PointOption.point(startX, startY)).waitAction(WaitOptions.waitOptions(Duration.ofSeconds(2)))
            .moveTo(PointOption.point(endX, endY)).release().perform();
            Thread.sleep(5000);
            try {
                b=driver.findElement(By.xpath("//android.widget.TextView[@content-desc='Sweep']")).isDisplayed();
                if(b) {
                    b=true;
                    break;
                }
                else {
                    continue;
                }
            }catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        driver.findElement(By.xpath("//android.widget.TextView[@content-desc='Sweep']")).click();

请帮助。谢谢enter image description here

1 个答案:

答案 0 :(得分:0)

使用基于UIAutomator的定位器会更可靠,因为您显然拥有可滚动的视图:

MobileElement element = (MobileElement) driver.findElement(MobileBy.AndroidUIAutomator(
        "new UiScrollable(new UiSelector().scrollable(true))" +
         ".scrollIntoView(new UiSelector().textContains(\"Sweep\"))"));

它不仅会滚动到元素,而且还要确保它在视口区域内并且可以交互。