使用ADB访问屏幕上的特定UI控件

Sid*_*kan 12 android adb buttonclick

adb shell控制台是否可以使用其ID访问Android应用程序的特定按钮?还是文字?

我正在尝试自动按下设备上的按钮.这是从浏览器访问的Web应用程序.所以,如果我有那个按钮ID,我可以向该按钮发送动作吗?

apr*_*cot 18

UI automator提供资源ID,文本和UI元素的边界.可以使用XML查看器或Chrome浏览器来更好地查看文件.

adb pull $(adb shell uiautomator dump | grep -oP '[^ ]+.xml') /tmp/view.xml
Run Code Online (Sandbox Code Playgroud)

可以提取UI元素的边界并且可以计算中点.更换text=resource-id=content-desc=需要.

coords=$(perl -ne 'printf "%d %d\n", ($1+$3)/2, ($2+$4)/2 if /text="MY_BUTTON_TEXT"[^>]*bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/' /tmp/view.xml)
Run Code Online (Sandbox Code Playgroud)

现在我们有UI元素中心的坐标,$coords我们只需要发送一个tap事件.

adb shell input tap $coords
Run Code Online (Sandbox Code Playgroud)

  • 这是一个更好的答案,准确地提供了通过 adb 获取 UI 元素边界的方法。出于某种原因,`($1+$2)/2, ($3+$4)/2` 没有按预期工作。我刚刚修复了只使用 $1, $3 的问题,因为第一个像素足以被点击:-) (2认同)
  • 这很棒,这是我选择的那个.但是......我决定更进一步,摆脱这个临时文件.转储时,可以指定要转储的文件,然后我再挖掘一下以找到代表stdout的设备.很快就变成了:'adb shell -x uiautomator dump/dev/fd/1`为了让adb shell的输出重定向到我们的主shell,需要-x选项 (2认同)

Nie*_*els 9

是的,你可以,虽然它不漂亮。

您可以使用以下命令获取视图层次结构:

adb exec-out uiautomator dump /dev/tty,它将输出作为 XML 文件打印到屏幕上。不幸的是,它不是有效的 XML,因为附加了一些文本。所以让我们过滤掉它:

adb exec-out uiautomator dump /dev/tty | awk '{gsub("UI hierchary dumped to: /dev/tty", "");print}'

现在我们有了一个有效的 XML。让我们通过 XPath 运行它:

adb exec-out uiautomator dump /dev/tty | awk '{gsub("UI hierchary dumped to: /dev/tty", "");print}' | xpath '//node[@resource-id="com.example:id/btnDone"]' 2> /dev/null,这将搜索具有特定 ID 的所有节点。现在你得到了节点,你可以做更多的事情。

如果您只获得视界,则必须执行以下操作:

adb exec-out uiautomator dump /dev/tty | awk '{gsub("UI hierchary dumped to: /dev/tty", "");print}' | xpath '//node[@resource-id="com.example:id/btnDone"]/@bounds' 2> /dev/null | awk '{$1=$1};1' | awk '{gsub("bounds=", "");print}' | awk '{gsub("\"", "");print}', 之后会清理字符串并只输出[294,1877][785,1981].

具体节点的来源是:

<node index="1" text="Let’s get started!" resource-id="com.example:id/btnDone" class="android.widget.Button" package="com.example" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[294,1877][785,1981]" />


pt2*_*121 8

我认为你能做的最好的事情就是根据坐标注入触摸.

请参阅从ADB向设备发送触摸事件使用ADB模拟触摸

您可以从dumpsys窗口或活动中获取按钮的坐标.

你也可以看看Monkeyrunner.


Ped*_*ito 5

您将无法使用按钮 id,但您可以获取按钮坐标并模拟点击事件。

Android 自带输入命令行工具,可以模拟各种输入事件。要模拟敲击,请使用:

input tap x y
Run Code Online (Sandbox Code Playgroud)

您可以使用 adb shell 远程运行命令:

adb shell input tap x y
Run Code Online (Sandbox Code Playgroud)

其他选项是:

shell@m0:/ $ input
input
usage: input ...
       input text <string>
       input keyevent <key code number or name>
       input [touchscreen|touchpad|touchnavigation] tap <x> <y>
       input [touchscreen|touchpad|touchnavigation] swipe <x1> <y1> <x2> <y2> [duration(ms)]
       input trackball press
       input trackball roll <dx> <dy>
Run Code Online (Sandbox Code Playgroud)