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

如何使用driver.find_elements_by方法返回除可变ID外的稳定属性如XPATH

问题解答

find_elements 系列方法的返回值固定为WebElement列表,没有内置参数可以直接修改为属性值列表,你只需在拿到元素列表后手动遍历提取需要的稳定属性即可

示例:提取所有匹配元素的XPATH列表

Android驱动中WebElement对象可直接通过get_attribute("xpath")获取绝对路径,该路径不受动态id影响,只要页面层级结构不变就长期稳定,代码如下:

listofblocks = driver1.find_elements_by_class_name("android.widget.RelativeLayout")
# 遍历提取所有元素的XPATH到新列表
xpath_list = [elem.get_attribute("xpath") for elem in listofblocks]
print(xpath_list)

其他可选稳定属性提取

如果不需要XPATH,也可以根据业务需求提取其他稳定属性:

  • 元素的无障碍标注content-desc:elem.get_attribute("contentDescription")
  • 元素展示的文本内容:elem.get_attribute("text")
  • 元素在屏幕上的坐标与尺寸:elem.location / elem.size

后续使用说明

提取到的属性列表可直接用于后续定位,比如需要再次定位列表中第2个元素时,直接调用:

target_elem = driver1.find_element_by_xpath(xpath_list[1])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 13:48:00