You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WinAppDriver的find_element_by_accessibility_id改为大小写不敏感函数

WinAppDriver桌面自动化:解决Accessibility ID大小写切换定位失败问题

解决方案1:使用XPath不区分大小写定位

利用XPath的translate函数将元素的AutomationId(对应WinAppDriver的accessibility id)和目标ID统一转换为相同大小写后匹配,彻底规避大小写变化的问题。示例代码:

# 先将目标ID转为小写
target_id = "SAMSUNGELECTRONICSCO.LTD.PCGallery_3c1yjt4zspk6g!App".lower()
# 通过XPath的translate函数把元素的AutomationId转为小写后匹配
element = self.find_element_by_xpath(f"//*[translate(@AutomationId, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='{target_id}']")

也可以统一转为大写,只需把lower()换成upper(),translate里的大小写字母顺序反过来即可。

解决方案2:封装容错查找方法

如果不想用XPath,可以封装一个自定义方法,依次尝试原ID、全小写ID、全大写ID,直到找到元素为止。示例代码:

from selenium.common.exceptions import NoSuchElementException

def find_element_by_accessibility_id_case_insensitive(self, target_id):
    # 尝试原ID
    try:
        return self.find_element_by_accessibility_id(target_id)
    except NoSuchElementException:
        pass
    # 尝试全小写ID
    try:
        return self.find_element_by_accessibility_id(target_id.lower())
    except NoSuchElementException:
        pass
    # 尝试全大写ID
    return self.find_element_by_accessibility_id(target_id.upper())

调用方式:

self.find_element_by_accessibility_id_case_insensitive("SAMSUNGELECTRONICSCO.LTD.PCGallery_3c1yjt4zspk6g!App")

这两种方法都能解决Accessibility ID大小写频繁切换导致的断言错误问题,其中XPath方法更高效,无需多次重试查找。

内容的提问来源于stack exchange,提问作者Conta Testes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:35:28