使用Appium与Robot Framework遍历RecyclerView并点击匹配条件的条目
解决方案
推荐方案:基于UiAutomator滚动定位(适配安卓RecyclerView场景,无需手写滑动逻辑)
安卓端的RecyclerView天然适配UiAutomator的UiScrollable滚动规则,直接构造定位逻辑即可实现自动滚动匹配,稳定性远高于自定义滑动循环,示例代码如下:
*** Keywords *** 点击匹配条件的RecyclerView条目 [Arguments] ${paramA} ${paramB} ${paramC} ${app_package} # 构造UiSelector规则,要求同时命中三个TextView的文本属性 ${target_locator}= Set Variable android=new UiScrollable(new UiSelector().scrollable(true)).scrollIntoView(new UiSelector().childSelector(new UiSelector().resourceId("${app_package}:id/tvA").text("${paramA}")).childSelector(new UiSelector().resourceId("${app_package}:id/tvB").text("${paramB}")).childSelector(new UiSelector().resourceId("${app_package}:id/tvC").text("${paramC}"))) # 定位到目标条目后点击 Wait Until Page Contains Element ${target_locator} timeout=10 Click Element ${target_locator}
备选方案:自定义滑动遍历逻辑(适配特殊需求场景)
如果需要自定义滑动规则,可按以下逻辑实现,避免索引失效、重复校验、死循环问题:
- 先通过
Get Element Location和Get Element Size获取RecyclerView的坐标与尺寸,确定滑动边界 - 每次滑动后记录当前页面所有条目的特征值,避免重复校验同一条目
- 当连续两次滑动后页面条目无变化,说明已滑到底部,直接终止循环
*** Keywords *** 自定义滑动查找目标条目 [Arguments] ${paramA} ${paramB} ${paramC} ${app_package} ${recycler_locator}=//androidx.recyclerview.widget.RecyclerView ${is_found}= Set Variable ${False} ${last_page_features}= Create List # 提前计算RecyclerView滑动坐标 ${recycler_rect}= Get Element Bounds ${recycler_locator} ${swipe_start_y}= Evaluate ${recycler_rect['bottom']} * 0.8 ${swipe_end_y}= Evaluate ${recycler_rect['top']} * 0.2 ${swipe_x}= Evaluate (${recycler_rect['left']} + ${recycler_rect['right']}) / 2 # 最多滑动30次避免死循环,可根据业务调整 FOR ${loop_count} IN RANGE 0 30 ${current_items}= Get WebElements ${recycler_locator}/* ${current_page_features}= Create List # 遍历当前页面所有可见条目 FOR ${item} IN @{current_items} ${textA}= Get Text ${item}//*[@resource-id="${app_package}:id/tvA"] ${textB}= Get Text ${item}//*[@resource-id="${app_package}:id/tvB"] ${textC}= Get Text ${item}//*[@resource-id="${app_package}:id/tvC"] # 匹配成功直接点击退出 IF "${textA}" == "${paramA}" and "${textB}" == "${paramB}" and "${textC}" == "${paramC}" Click Element ${item} ${is_found}= Set Variable ${True} BREAK END Append To List ${current_page_features} ${textA}${textB}${textC} END IF ${is_found} Return From Keyword END # 判断是否滑到底部 Sort List ${last_page_features} Sort List ${current_page_features} Run Keyword If Lists Are Equal ${last_page_features} ${current_page_features} Fail 已滑至底部,未找到符合条件的条目 # 更新缓存执行滑动 ${last_page_features}= Copy List ${current_page_features} Swipe ${swipe_x} ${swipe_start_y} ${swipe_x} ${swipe_end_y} duration=500 Sleep 0.5 END Fail 达到最大滑动次数,未找到符合条件的条目
注意事项
- 不要使用固定索引
item[${i}]判断条目是否存在,RecyclerView的条目索引会随滑动动态回收复用,固定索引定位会出现匹配错误 - 上面代码中的
${app_package}替换为你测试应用的实际包名即可使用 - 无特殊需求优先使用推荐方案,UiAutomator底层已处理了滑动边界、速度等细节,稳定性更高
内容的提问来源于stack exchange,提问作者Pandarian Ld
相关产品推荐
相关产品推荐

