如何在Appium中使用AndroidUIAutomator按部分resource ID查找Android元素?
基于Resource ID前缀匹配查找Appium Android元素的C#实现
你可以通过UIAutomator选择器实现前缀匹配,这是Android平台下性能最优的方案,不需要遍历所有元素:
方法1:UIAutomator正则匹配(推荐)
Android UIAutomator原生支持通过正则匹配resourceId,你直接在已定位到的第一条通知父元素下调用对应查找方法即可:
// 假设你已经定位到了第一条通知的父元素 var firstNotification = driver.FindElementById("你已定位到的第一条通知项的ID"); // 通过前缀匹配查找标题元素,两种写法均可 // 写法1:专用Android定位方法 var titleElement = firstNotification.FindElementByAndroidUIAutomator(@" new UiSelector().resourceIdMatches(""^notification-title-.+$"") "); // 写法2:通用By定位器,兼容性更强 var titleElement = firstNotification.FindElement(By.AndroidUIAutomator(@" new UiSelector().resourceIdMatches(""^notification-title-.+$"") ")); // 获取标题文本 string notificationTitle = titleElement.Text;
上面正则里的^表示匹配字符串开头,.+表示匹配后面的任意非空字符,可以精准匹配notification-title-开头后跟6位数字的ID格式。
方法2:遍历过滤(仅适合少量元素场景)
如果因为环境限制无法使用UIAutomator选择器,也可以先获取父元素下所有子元素,再过滤ResourceId属性:
var firstNotification = driver.FindElementById("你已定位到的第一条通知项的ID"); var allChildren = firstNotification.FindElements(By.XPath(".//*")); var titleElement = allChildren.FirstOrDefault(e => e.GetAttribute("resourceId").StartsWith("notification-title-")); if(titleElement != null) { string notificationTitle = titleElement.Text; }
注意事项
- 上述UIAutomator方案仅适用于Android平台,iOS平台需要改用NSPredicate谓词匹配实现
- 确保你的测试项目引用的
Appium.WebDriverNuGet包版本在4.0以上,Appium服务端启用UIAutomator2驱动(目前新版Appium默认启用)
内容的提问来源于stack exchange,提问作者Isaac056
相关产品推荐
相关产品推荐

