跳到主要内容

文本约束 (Selector.text)

Selector.text

声明

node.selector():text(text)
node.selector():text_contains(text)
node.selector():text_starts_with(text)
node.selector():text_ends_with(text)
node.selector():text_matches(regex)

参数

参数类型说明
textstring文本内容
regexstring正则表达式

返回值

类型说明
Selector选择器对象(支持链式调用)

说明

通过控件的文本内容(text 属性)约束控件。

方法变体:

  • text(str) - 精确匹配,文本必须完全相等
  • text_contains(str) - 包含匹配,文本包含指定字符串
  • text_starts_with(str) - 前缀匹配,文本以指定字符串开头
  • text_ends_with(str) - 后缀匹配,文本以指定字符串结尾
  • text_matches(regex) - 正则匹配,文本符合正则表达式

适用场景:

  • 按钮、标签等显示文字的控件
  • 动态内容中查找特定文本
  • 无 ID 时的备选定位方式

注意事项:

  • 文本匹配区分大小写
  • 某些控件的文本可能包含不可见字符(如换行符)
  • 图片按钮等控件可能没有 text 属性,需使用 desc
  • 国际化应用的文本会随语言变化,建议优先使用 ID
  • 正则表达式中的特殊字符需要转义(如 \\d 表示数字)

与 desc 的区别:

  • text - 控件显示的文本内容
  • desc - 控件的无障碍描述(content-description)
待实现

该接口正在开发中。

示例

local node = require("node")

-- 精确匹配
local n = node.selector():text("确定"):find()

-- 包含匹配
local n2 = node.selector():text_contains("登录"):find()

-- 正则匹配
local n3 = node.selector():text_matches("\\d+元"):find()

AScript 对应

# AScript (Python)
from ascript.android.node import Selector

node = Selector().text("确定").find()
node = Selector().textContains("登录").find()