无法使用 Appium Selenium Android 在 ListView 中滚动元素



几天来,我试图找到一个简单的解决方案来在列表视图中滚动

由于该 Appium 检查器不提供列表的所有元素(仅通过手动滑动和刷新检查器,因此将加载具有新实例的新元素。

经过研究,我发现列表项之间的距离如下:

Item Location= (15, 828)
Item Location= (15, 1209)
Item Location= (15, 1590)

所以我想每次点击都需要向下滚动 381 像素,经过这么多次尝试,我找不到这部分代码的解决方案,如果有人能提供帮助,我会很高兴:

List<WebElement> list = driver.findElements(By.id("net.balink.diplomat.qa:id/btnAddToCart"));
System.out.println("List Size is= " + list.size());
for (int j = 0; j < list.size(); j++) {
WebElement listItem = list.get(j);
Point location = listItem.getLocation();
System.out.println("Location= " + location);
listItem.click();
//to do here: swipe 381 px down after any click, then re-initialize 
//the listItem in order to get a new index - and the loop when 
//theres no more list items
Thread.sleep(2000);
}

我使用以下方法来滚动屏幕:

public static MobileElement scrollElementByContentDesc(String scrollableList, String uiSelector, String textToSearchInList) {
return driver.findElement(MobileBy.AndroidUIAutomator(
"new UiScrollable(new UiSelector().resourceId("" + scrollableList + "")).getChildByDescription("
+ "new UiSelector().className("" + uiSelector + ""), "" + textToSearchInList+ "")"));
}

可滚动列表是可滚动列表元素的 id,

uiSelector是列表项的类名,

textToSearchInList可以是您需要在列表中搜索的任何文本。如果您的目的只是滚动到列表末尾,它可以是任何随机文本。

从任何方法调用此方法:

public void someMethod(){
//other code
try{
MobileElement element= scrollElementByContentDesc("your scrollableList id",
"uiSelector classname", "any text you need to find in the list);
}catch(Exception e){
//do nothing
}
}

如果你想通过 co0rdinate 滑动,你可以这样做。

import io.appium.java_client.TouchAction;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import java.util.concurrent.TimeUnit;
import static java.time.Duration.ofSeconds;
TouchAction action = new TouchAction(driver); 
action.press(PointOption.point(115, 650)).waitAction(WaitOptions.waitOptions(ofSeconds(1)))
.moveTo(PointOption.point(115, 350)).release().perform();

确保导入正确的库。

更可靠的方法是使用本机 UiAutomator 方式:

因此,首先找到具有scrollable: true属性的列表元素的父视图。这绝对应该至少是一个。

然后使用检查器构建和测试您的UiAutomator定位器

MobileElement elementScrollTo = driver
.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()"
+ ".resourceId("android:id/list")).scrollIntoView("
+ "new UiSelector().text("Some text"));");

UiSelector有相当丰富的API,检查它并找到最适合您的。

这种方法比触摸操作更好,因为您不依赖于设备屏幕分辨率/坐标。

最新更新