uiautomator2


Nameuiautomator2 JSON
Version 3.2.8 PyPI version JSON
download
home_pagehttps://github.com/openatx/uiautomator2
Summaryuiautomator for android device
upload_time2024-12-05 14:28:01
maintainerNone
docs_urlNone
authorcodeskyblue
requires_python<4.0,>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # uiautomator2
[![PyPI](https://img.shields.io/pypi/v/uiautomator2.svg)](https://pypi.python.org/pypi/uiautomator2)
![PyPI](https://img.shields.io/pypi/pyversions/uiautomator2.svg)
[![codecov](https://codecov.io/gh/openatx/uiautomator2/graph/badge.svg?token=d0ZLkqorBu)](https://codecov.io/gh/openatx/uiautomator2)

QQ交流群: **815453846**
Discord: <https://discord.gg/PbJhnZJKDd>

> 有段时间没有维护这个项目了(可能有两年了),但是最近工作需要又重新研究一下Android原生自动化,当然又调研了Appium,对比下来一看,发现uiautomator2这个项目的运行速度是真的好快,从检测元素到点击,都是毫秒级的,代码也比较好理解。真是没想到以前竟然写出了这么神奇的项目,这么好的项目怎么能让它落灰呢,得好好整一整,一些垃圾代码清理清理。所以项目版本从2.x.x升级到了3.x.x

还在用2.x.x版本的用户,可以先看一下[2to3](docs/2to3.md) 再决定是否要升级3.x.x (我个人还是非常建议升级的)

2到3毕竟是大版本升级,很多的函数删掉了。首先删掉的就是atx-agent,其次还有一堆atx-agent相关的函数。废弃的功能比如init.

各种依赖库的版本号

- [![PyPI](https://img.shields.io/pypi/v/uiautomator2.svg?label=uiautomator2)](https://pypi.python.org/pypi/uiautomator2)
- [![PyPI](https://img.shields.io/pypi/v/adbutils.svg?label=adbutils)](https://github.com/openatx/adbutils)
- [![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/openatx/android-uiautomator-server.svg?label=android-uiautomator-server)](https://github.com/openatx/android-uiautomator-server)
- ~~[![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/openatx/atx-agent.svg?label=atx-agent)](https://github.com/openatx/atx-agent)~~

[UiAutomator](https://developer.android.com/training/testing/ui-automator.html)是Google提供的用来做安卓自动化测试的一个Java库,基于Accessibility服务。功能很强,可以对第三方App进行测试,获取屏幕上任意一个APP的任意一个控件属性,并对其进行任意操作,但有两个缺点:1. 测试脚本只能使用Java语言 2. 测试脚本要打包成jar或者apk包上传到设备上才能运行。

我们希望测试逻辑能够用Python编写,能够在电脑上运行的时候就控制手机。这里要非常感谢 Xiaocong He ([@xiaocong][]),他将这个想法实现了出来(见[xiaocong/uiautomator](https://github.com/xiaocong/uiautomator)),原理是在手机上运行了一个http rpc服务,将uiautomator中的功能开放出来,然后再将这些http接口封装成Python库。
因为`xiaocong/uiautomator`这个库,已经很久不见更新。所以我们直接fork了一个版本,为了方便做区分我们就在后面加了个2 [openatx/uiautomator2](https://github.com/openatx/uiautomator2),对应的Android包源码我也fork了一份,[openatx/android-uiautomator-server](https://github.com/openatx/android-uiautomator-server)

除了对原有的库的bug进行了修复,还增加了很多新的Feature。主要有以下部分:

* ~~设备和开发机可以脱离数据线,通过WiFi互联(基于[atx-agent](https://github.com/openatx/atx-agent)~~
* ~~集成了[openstf/minicap](https://github.com/openstf/minicap)达到实时屏幕投频,以及实时截图~~
* ~~集成了[openstf/minitouch](https://github.com/openstf/minitouch)达到精确实时控制设备~~
* 修复了[xiaocong/uiautomator](https://github.com/xiaocong/uiautomator)经常性退出的问题
* 代码进行了重构和精简,方便维护
* 实现了一个设备管理平台(也支持iOS) [atxserver2](https://github.com/openatx/atxserver2) (注:目前不怎么维护了)
* 扩充了toast获取和展示的功能(需要手动开启ATX的悬浮窗权限) 貌似有bug用不了

>这里要先说明下,因为经常有很多人问 openatx/uiautomator2 并不支持iOS测试,需要iOS自动化测试,可以转到这个库 [openatx/facebook-wda](https://github.com/openatx/facebook-wda)。

> PS: 这个库 ~~<https://github.com/NeteaseGame/ATX>~~ 目前已经不维护了,请尽快更换。

这里有一份快速参考,适合已经入门的人 [QUICK REFERENCE GUIDE](QUICK_REFERENCE.md),欢迎多提意见。

## Requirements
- Android版本 4.4+
- Python 3.8+

## QUICK START
先准备一台(不要两台)开启了`开发者选项`的安卓手机,连接上电脑,确保执行`adb devices`可以看到连接上的设备。

运行`pip3 install -U uiautomator2` 安装uiautomator2

命令行运行`python`打开python交互窗口。然后将下面的命令输入到窗口中。

```python
import uiautomator2 as u2

d = u2.connect() # connect to device
print(d.info)
```

这时看到类似下面的输出,就可以正式开始用我们这个库了。因为这个库功能太多,后面还有很多的内容,需要慢慢去看 ....

```
{'currentPackageName': 'net.oneplus.launcher', 'displayHeight': 1920, 'displayRotation': 0, 'displaySizeDpX': 411, 'displaySizeDpY': 731, 'displayWidth': 1080, 'productName': 'OnePlus5', '
screenOn': True, 'sdkInt': 27, 'naturalOrientation': True}
```

另外为了保持稳定,还需要开启`小黄车`的悬浮窗权限。参考文章 [py-uiautomator2通过悬浮窗让服务长时间可用](https://zhuanlan.zhihu.com/p/688009468)

一般情况下都会成功,不过也可能会有意外。可以加QQ群反馈问题(群号在最上面),群里有很多大佬可以帮你解决问题。

## Sponsors
Thank you to all our sponsors! ✨🍰✨

### 金牌赞助商(Gold Sponsor)
Empty

# Article Recommended
优秀文章推荐 (欢迎QQ群里at我反馈)

- [termux里如何部署uiautomator2简介](https://www.cnblogs.com/ze-yan/p/12242383.html) by `成都-测试只会一点点`

## 相关项目
- 基于adb协议与Android进行交互的库 [adbutils](https://github.com/openatx/adbutils)
- [uiauto.dev](https://uiauto.dev) 用于查看UI层级结构,类似于uiautomatorviewer(用于替代之前写的weditor),用于查看UI层级结构 
- 设备管理平台,设备多了就会用到 [atxserver2](https://github.com/openatx/atxserver2) (寻找项目维护人员)
- ~~[atx-agent](https://github.com/openatx/atx-agent) 运行在设备上的驻守程序,go开发,用于保活设备上相关的服务~~
- ~~[weditor](https://github.com/openatx/weditor) 类似于uiautomatorviewer,专门为本项目开发的辅助编辑器(这个暂不维护了~~

**[Installation](#installation)**

**[Connect to a device](#connect-to-a-device)**

**[Command line](#command-line)**

**[Global settings](#global-settings)**
  - **[Debug HTTP requests](#debug-http-requests)**
  - **[Implicit wait](#implicit-wait)**

**[App management](#app-management)**
  - **[Install an app](#install-an-app)**
  - **[Launch an app](#launch-an-app)**
  - **[Stop an app](#stop-an-app)**
  - **[Stop all running apps](#stop-all-running-apps)**
  - **[Push and pull files](#push-and-pull-files)**
  - **[Other app operations](#other-app-operations)**

**[UI automation](#basic-api-usages)**
  - **[Shell commands](#shell-commands)**
  - **[Session](#session)**
  - **[Retrieve the device info](#retrieve-the-device-info)**
  - **[Key Events](#key-events)**
  - **[Gesture interaction with the device](#gesture-interaction-with-the-device)**
  - **[Screen-related](#screen-related)**
  - **[Selector](#selector)**
  - **[Watcher](#watcher)**
  - **[Global settings](#global-settings)**
  - **[Input method](#input-method)**
  - **[Toast](#toast)**
  - **[XPath](#xpath)**
  - **[Screenrecord](#screenrecord)**
  - **[Image match](#image-match) Removed**


**[Contributors](#contributors)**

**[LICENSE](#license)**


# Installation
1. Install uiautomator2

    ```bash
    pip install -U uiautomator2
    ```
    
    测试是否安装成功 `uiautomator2 --help`
    
2. UI Inspector

    ```bash
    pip install uiautodev
    # 启动
    uiauto.dev
    ```

    浏览器打开 https://uiauto.dev 查看当前设备的界面结构。

    **uiauto.dev**

    [uiauto.dev](https://github.com/codeskyblue/uiauto.dev) 是一个独立与uiautomator2之外的一个项目,用于查看图层结构的。属于旧版项目[weditor的重构版本](https://github.com/openatx/weditor),后续也许会收费(价格肯定物超所值),来支持当前这个项目继续维护下去。感兴趣的可以加群讨论(也包含提需求) QQ群 536481989

# Connect to a device
use serialno to connect device eg. `123456f` (seen from `adb devices`)

```python
import uiautomator2 as u2

d = u2.connect('123456f') # alias for u2.connect_usb('123456f')
print(d.info)
```

Serial can be passed through env-var `ANDROID_SERIAL`


```python
# export ANDROID_SERIAL=123456f
d = u2.connect()
```

# Command line
其中的`$device_ip`代表设备的ip地址

如需指定设备需要传入`--serial` 如 `python3 -m uiautomator2 --serial bff1234 <SubCommand>`, SubCommand为子命令(screenshot, current 等)

> 1.0.3 Added: `python3 -m uiautomator2` equals to `uiautomator2`

- screenshot: 截图

    ```bash
    $ uiautomator2 screenshot screenshot.jpg
    ```

- current: 获取当前包名和activity

    ```bash
    $ uiautomator2 current
    {
        "package": "com.android.browser",
        "activity": "com.uc.browser.InnerUCMobile",
        "pid": 28478
    }
    ```
    
- uninstall: Uninstall app

    ```bash
    $ uiautomator2 uninstall <package-name> # 卸载一个包
    $ uiautomator2 uninstall <package-name-1> <package-name-2> # 卸载多个包
    $ uiautomator2 uninstall --all # 全部卸载
    ```

- stop: Stop app

    ```bash
    $ uiautomator2 stop com.example.app # 停止一个app
    $ uiautomator2 stop --all # 停止所有的app
    ```

- doctor:

    ```bash
    $ uiautomator2 doctor
    [I 2024-04-25 19:53:36,288 __main__:101 pid:15596] uiautomator2 is OK
    ```
    
# API Documents

### New command timeout (Removed)
When python quit, the UiAutomation service also quit.
<!-- How long (in seconds) will wait for a new command from the client before assuming the client quit and ending the uiautomator service (Default 3 minutes)

配置accessibility服务的最大空闲时间,超时将自动释放。默认3分钟。

```python
d.set_new_command_timeout(300) # change to 5 minutes, unit seconds
``` -->

### Debug HTTP requests
打印出代码背后的HTTP请求信息

```python
>>> d.debug = True
>>> d.info
12:32:47.182 $ curl -X POST -d '{"jsonrpc": "2.0", "id": "b80d3a488580be1f3e9cb3e926175310", "method": "deviceInfo", "params": {}}' 'http://127.0.0.1:54179/jsonrpc/0'
12:32:47.225 Response >>>
{"jsonrpc":"2.0","id":"b80d3a488580be1f3e9cb3e926175310","result":{"currentPackageName":"com.android.mms","displayHeight":1920,"displayRotation":0,"displaySizeDpX":360,"displaySizeDpY":640,"displayWidth":1080,"productName"
:"odin","screenOn":true,"sdkInt":25,"naturalOrientation":true}}
<<< END
```

### Implicit wait
设置元素查找等待时间(默认20s)

```python
d.implicitly_wait(10.0) # 也可以通过d.settings['wait_timeout'] = 10.0 修改
d(text="Settings").click() # if Settings button not show in 10s, UiObjectNotFoundError will raised

print("wait timeout", d.implicitly_wait()) # get default implicit wait
```

This function will have influence on `click`, `long_click`, `drag_to`, `get_text`, `set_text`, `clear_text`, etc.

## App management
This part showcases how to perform app management

### Install an app
We only support installing an APK from a URL

```python
d.app_install('http://some-domain.com/some.apk')
```

### Launch an app
```python
# 默认的这种方法是先通过atx-agent解析apk包的mainActivity,然后调用am start -n $package/$activity启动
d.app_start("com.example.hello_world")

# 使用 monkey -p com.example.hello_world -c android.intent.category.LAUNCHER 1 启动
# 这种方法有个副作用,它自动会将手机的旋转锁定给关掉
d.app_start("com.example.hello_world", use_monkey=True) # start with package name

# 通过指定main activity的方式启动应用,等价于调用am start -n com.example.hello_world/.MainActivity
d.app_start("com.example.hello_world", ".MainActivity")
```

### Stop an app
```python
# equivalent to `am force-stop`, thus you could lose data
d.app_stop("com.example.hello_world") 
# equivalent to `pm clear`
d.app_clear('com.example.hello_world')
```

### Stop all running apps
```python
# stop all
d.app_stop_all()
# stop all app except for com.examples.demo
d.app_stop_all(excludes=['com.examples.demo'])
```

### Get app info
```python
d.app_info("com.examples.demo")
# expect output
#{
#    "mainActivity": "com.github.uiautomator.MainActivity",
#    "label": "ATX",
#    "versionName": "1.1.7",
#    "versionCode": 1001007,
#    "size":1760809
#}

# save app icon
img = d.app_icon("com.examples.demo")
img.save("icon.png")
```

### List all running apps
```python
d.app_list_running()
# expect output
# ["com.xxxx.xxxx", "com.github.uiautomator", "xxxx"]
```

### Wait until app running
```python
pid = d.app_wait("com.example.android") # 等待应用运行, return pid(int)
if not pid:
    print("com.example.android is not running")
else:
    print("com.example.android pid is %d" % pid)

d.app_wait("com.example.android", front=True) # 等待应用前台运行
d.app_wait("com.example.android", timeout=20.0) # 最长等待时间20s(默认)
```

> Added in version 1.2.0

### Push and pull files
* push a file to the device

    ```python
    # push to a folder
    d.push("foo.txt", "/sdcard/")
    # push and rename
    d.push("foo.txt", "/sdcard/bar.txt")
    # push fileobj
    with open("foo.txt", 'rb') as f:
        d.push(f, "/sdcard/")
    # push and change file access mode
    d.push("foo.sh", "/data/local/tmp/", mode=0o755)
    ```

* pull a file from the device

    ```python
    d.pull("/sdcard/tmp.txt", "tmp.txt")

    # FileNotFoundError will raise if the file is not found on the device
    d.pull("/sdcard/some-file-not-exists.txt", "tmp.txt")
    ```

### Other app operations

```python
# grant all the permissions
d.app_auto_grant_permissions("io.appium.android.apis")

# open scheme
d.open_url("appname://appnamehost")
# same as
# adb shell am start -a android.intent.action.VIEW -d "appname://appnamehost"
```

## Basic API Usages
This part showcases how to perform common device operations:

### Shell commands
* Run a short-lived shell command with a timeout protection. (Default timeout 60s)

    Note: timeout support require `atx-agent >=0.3.3`

    `adb_shell` function is deprecated. Use `shell` instead.

    Simple usage

    ```python
    output, exit_code = d.shell("pwd", timeout=60) # timeout 60s (Default)
    # output: "/\n", exit_code: 0
    # Similar to command: adb shell pwd

    # Since `shell` function return type is `namedtuple("ShellResponse", ("output", "exit_code"))`
    # so we can do some tricks
    output = d.shell("pwd").output
    exit_code = d.shell("pwd").exit_code
    ```

    The first argument can be list. for example

    ```python
    output, exit_code = d.shell(["ls", "-l"])
    # output: "/....", exit_code: 0
    ```

   This returns a string for stdout merged with stderr.
   If the command is a blocking command, `shell` will also block until the command is completed or the timeout kicks in. No partial output will be received during the execution of the command. This API is not suitable for long-running commands. The shell command given runs in a similar environment of `adb shell`, which has a Linux permission level of `adb` or `shell` (higher than an app permission).

* Run a long-running shell command (Removed)
<!-- 
    add stream=True will return `requests.models.Response` object. More info see [requests stream](http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#id5)

    ```python
    r = d.shell("logcat", stream=True)
    # r: requests.models.Response
    deadline = time.time() + 10 # run maxium 10s
    try:
        for line in r.iter_lines(): # r.iter_lines(chunk_size=512, decode_unicode=None, delimiter=None)
            if time.time() > deadline:
                break
            print("Read:", line.decode('utf-8'))
    finally:
        r.close() # this method must be called
    ```

    Command will be terminated when `r.close()` called. -->
    
### Session
Session represent an app lifecycle. Can be used to start app, detect app crash.

* Launch and close app

    ```python
    sess = d.session("com.netease.cloudmusic") # start 网易云音乐
    sess.close() # 停止网易云音乐
    sess.restart() # 冷启动网易云音乐
    ```

* Use python `with` to launch and close app

    ```python
    with d.session("com.netease.cloudmusic") as sess:
        sess(text="Play").click()
    ```

* Attach to the running app

    ```python
    # launch app if not running, skip launch if already running
    sess = d.session("com.netease.cloudmusic", attach=True)
    ```

* Detect app crash

    ```python
    # When app is still running
    sess(text="Music").click() # operation goes normal

    # If app crash or quit
    sess(text="Music").click() # raise SessionBrokenError
    # other function calls under session will raise SessionBrokenError too
    ```

    ```python
    # check if session is ok.
    # Warning: function name may change in the future
    sess.running() # True or False
    ```


### Retrieve the device info

Get basic information

```python
d.info
```

Below is a possible output:

```
{'currentPackageName': 'com.android.systemui',
 'displayHeight': 1560,
 'displayRotation': 0,
 'displaySizeDpX': 360,
 'displaySizeDpY': 780,
 'displayWidth': 720,
 'naturalOrientation': True,
 'productName': 'ELE-AL00',
 'screenOn': True,
 'sdkInt': 29}
```

Get window size

```python
print(d.window_size())
# device upright output example: (1080, 1920)
# device horizontal output example: (1920, 1080)
```

Get current app info. For some android devices, the output could be empty (see *Output example 3*)

```python
print(d.app_current())
# Output example 1: {'activity': '.Client', 'package': 'com.netease.example', 'pid': 23710}
# Output example 2: {'activity': '.Client', 'package': 'com.netease.example'}
# Output example 3: {'activity': None, 'package': None}
```

Wait activity

```python
d.wait_activity(".ApiDemos", timeout=10) # default timeout 10.0 seconds
# Output: true of false
```

Get device serial number

```python
print(d.serial)
# output example: 74aAEDR428Z9
```

Get WLAN ip

```python
print(d.wlan_ip)
# output example: 10.0.0.1 or None
```


~~Get detailed device info~~ `d.device_info`

device_info

```python
print(d.device_info)
```

Below is a possible output:

```
{'arch': 'arm64-v8a',
 'brand': 'google',
 'model': 'sdk_gphone64_arm64',
 'sdk': 34,
 'serial': 'EMULATOR34X1X19X0',
 'version': 14}
```

### Clipboard
Get of set clipboard content

设置粘贴板内容或获取内容

* clipboard/set_clipboard

    ```python
    d.clipboard = 'hello-world'
    # or
    d.set_clipboard('hello-world', 'label')

    ```

Get clipboard content

>  get clipboard requires IME(com.github.uiautomator/.AdbKeyboard) call `d.set_input_ime()` before using it.

    ```python
    
    # get clipboard content
    print(d.clipboard)
    ```

### Key Events

* Turn on/off screen

    ```python
    d.screen_on() # turn on the screen
    d.screen_off() # turn off the screen
    ```

* Get current screen status

    ```python
    d.info.get('screenOn') # require Android >= 4.4
    ```

* Press hard/soft key

    ```python
    d.press("home") # press the home key, with key name
    d.press("back") # press the back key, with key name
    d.press(0x07, 0x02) # press keycode 0x07('0') with META ALT(0x02)
    ```

* These key names are currently supported:

    - home
    - back
    - left
    - right
    - up
    - down
    - center
    - menu
    - search
    - enter
    - delete ( or del)
    - recent (recent apps)
    - volume_up
    - volume_down
    - volume_mute
    - camera
    - power

You can find all key code definitions at [Android KeyEvnet](https://developer.android.com/reference/android/view/KeyEvent.html)

* Unlock screen

    ```python
    d.unlock()
    # This is equivalent to
    # 1. press("power")
    # 2. swipe from left-bottom to right-top
    ```

### Gesture interaction with the device
* Click on the screen

    ```python
    d.click(x, y)
    ```

* Double click

    ```python
    d.double_click(x, y)
    d.double_click(x, y, 0.1) # default duration between two click is 0.1s
    ```

* Long click on the screen

    ```python
    d.long_click(x, y)
    d.long_click(x, y, 0.5) # long click 0.5s (default)
    ```

* Swipe

    ```python
    d.swipe(sx, sy, ex, ey)
    d.swipe(sx, sy, ex, ey, 0.5) # swipe for 0.5s(default)
    ```

* SwipeExt 扩展功能

    ```python
    d.swipe_ext("right") # 手指右滑,4选1 "left", "right", "up", "down"
    d.swipe_ext("right", scale=0.9) # 默认0.9, 滑动距离为屏幕宽度的90%
    d.swipe_ext("right", box=(0, 0, 100, 100)) # 在 (0,0) -> (100, 100) 这个区域做滑动

	# 实践发现上滑或下滑的时候,从中点开始滑动成功率会高一些
	d.swipe_ext("up", scale=0.8) # 代码会vkk

    # 还可以使用Direction作为参数
    from uiautomator2 import Direction
    
    d.swipe_ext(Direction.FORWARD) # 页面下翻, 等价于 d.swipe_ext("up"), 只是更好理解
    d.swipe_ext(Direction.BACKWARD) # 页面上翻
    d.swipe_ext(Direction.HORIZ_FORWARD) # 页面水平右翻
    d.swipe_ext(Direction.HORIZ_BACKWARD) # 页面水平左翻
    ```

* Drag

    ```python
    d.drag(sx, sy, ex, ey)
    d.drag(sx, sy, ex, ey, 0.5) # swipe for 0.5s(default)

* Swipe points

    ```python
    # swipe from point(x0, y0) to point(x1, y1) then to point(x2, y2)
    # time will speed 0.2s bwtween two points
    d.swipe_points([(x0, y0), (x1, y1), (x2, y2)], 0.2))
    ```

    多用于九宫格解锁,提前获取到每个点的相对坐标(这里支持百分比),
    更详细的使用参考这个帖子 [使用u2实现九宫图案解锁](https://testerhome.com/topics/11034)

* Touch and drap (Beta)

    这个接口属于比较底层的原始接口,感觉并不完善,不过凑合能用。注:这个地方并不支持百分比

    ```python
    d.touch.down(10, 10) # 模拟按下
    time.sleep(.01) # down 和 move 之间的延迟,自己控制
    d.touch.move(15, 15) # 模拟移动
    d.touch.up(10, 10) # 模拟抬起
    ```

Note: click, swipe, drag operations support percentage position values. Example:

`d.long_click(0.5, 0.5)` means long click center of screen

### Screen-related
* Retrieve/Set device orientation

    The possible orientations:

    -   `natural` or `n`
    -   `left` or `l`
    -   `right` or `r`
    -   `upsidedown` or `u` (can not be set)

    ```python
    # retrieve orientation. the output could be "natural" or "left" or "right" or "upsidedown"
    orientation = d.orientation

    # WARNING: not pass testing in my TT-M1
    # set orientation and freeze rotation.
    # notes: setting "upsidedown" requires Android>=4.3.
    d.set_orientation('l') # or "left"
    d.set_orientation("l") # or "left"
    d.set_orientation("r") # or "right"
    d.set_orientation("n") # or "natural"
    ```

* Freeze/Un-freeze rotation

    ```python
    # freeze rotation
    d.freeze_rotation()
    # un-freeze rotation
    d.freeze_rotation(False)
    ```

* Take screenshot

    ```python
    # take screenshot and save to a file on the computer, require Android>=4.2.
    d.screenshot("home.jpg")
    
    # get PIL.Image formatted images. Naturally, you need pillow installed first
    image = d.screenshot() # default format="pillow"
    image.save("home.jpg") # or home.png. Currently, only png and jpg are supported

    # get opencv formatted images. Naturally, you need numpy and cv2 installed first
    import cv2
    image = d.screenshot(format='opencv')
    cv2.imwrite('home.jpg', image)

    # get raw jpeg data
    imagebin = d.screenshot(format='raw')
    open("some.jpg", "wb").write(imagebin)
    ```

* Dump UI hierarchy

    ```python
    # get the UI hierarchy dump content
    xml = d.dump_hierarchy()

    # compressed=True: include not import nodes
    # pretty: format xml
    # max_depth: limit xml depth, default 50
    xml = d.dump_hierarchy(compressed=False, pretty=False, max_depth=50)
    ```

* Open notification or quick settings

    ```python
    d.open_notification()
    d.open_quick_settings()
    ```

### Selector

Selector is a handy mechanism to identify a specific UI object in the current window.

```python
# Select the object with text 'Clock' and its className is 'android.widget.TextView'
d(text='Clock', className='android.widget.TextView')
```

Selector supports below parameters. Refer to [UiSelector Java doc](http://developer.android.com/tools/help/uiautomator/UiSelector.html) for detailed information.

*  `text`, `textContains`, `textMatches`, `textStartsWith`
*  `className`, `classNameMatches`
*  `description`, `descriptionContains`, `descriptionMatches`, `descriptionStartsWith`
*  `checkable`, `checked`, `clickable`, `longClickable`
*  `scrollable`, `enabled`,`focusable`, `focused`, `selected`
*  `packageName`, `packageNameMatches`
*  `resourceId`, `resourceIdMatches`
*  `index`, `instance`

#### Children and siblings

* children

  ```python
  # get the children or grandchildren
  d(className="android.widget.ListView").child(text="Bluetooth")
  ```

* siblings

  ```python
  # get siblings
  d(text="Google").sibling(className="android.widget.ImageView")
  ```

* children by text or description or instance

  ```python
  # get the child matching the condition className="android.widget.LinearLayout"
  # and also its children or grandchildren with text "Bluetooth"
  d(className="android.widget.ListView", resourceId="android:id/list") \
   .child_by_text("Bluetooth", className="android.widget.LinearLayout")

  # get children by allowing scroll search
  d(className="android.widget.ListView", resourceId="android:id/list") \
   .child_by_text(
      "Bluetooth",
      allow_scroll_search=True,
      className="android.widget.LinearLayout"
    )
  ```

  - `child_by_description` is to find children whose grandchildren have
      the specified description, other parameters being similar to `child_by_text`.

  - `child_by_instance` is to find children with has a child UI element anywhere
      within its sub hierarchy that is at the instance specified. It is performed
      on visible views **without scrolling**.

  See below links for detailed information:

  -   [UiScrollable](http://developer.android.com/tools/help/uiautomator/UiScrollable.html), `getChildByDescription`, `getChildByText`, `getChildByInstance`
  -   [UiCollection](http://developer.android.com/tools/help/uiautomator/UiCollection.html), `getChildByDescription`, `getChildByText`, `getChildByInstance`

  Above methods support chained invoking, e.g. for below hierarchy

  ```xml
  <node index="0" text="" resource-id="android:id/list" class="android.widget.ListView" ...>
    <node index="0" text="WIRELESS & NETWORKS" resource-id="" class="android.widget.TextView" .../>
    <node index="1" text="" resource-id="" class="android.widget.LinearLayout" ...>
      <node index="1" text="" resource-id="" class="android.widget.RelativeLayout" ...>
        <node index="0" text="Wi‑Fi" resource-id="android:id/title" class="android.widget.TextView" .../>
      </node>
      <node index="2" text="ON" resource-id="com.android.settings:id/switchWidget" class="android.widget.Switch" .../>
    </node>
    ...
  </node>
  ```
  ![settings](https://raw.github.com/xiaocong/uiautomator/master/docs/img/settings.png)

  To click the switch widget right to the TextView 'Wi‑Fi', we need to select the switch widgets first. However, according to the UI hierarchy, more than one switch widgets exist and have almost the same properties. Selecting by className will not work. Alternatively, the below selecting strategy would help:

  ```python
  d(className="android.widget.ListView", resourceId="android:id/list") \
    .child_by_text("Wi‑Fi", className="android.widget.LinearLayout") \
    .child(className="android.widget.Switch") \
    .click()
  ```

* relative positioning

  Also we can use the relative positioning methods to get the view: `left`, `right`, `top`, `bottom`.

  -   `d(A).left(B)`, selects B on the left side of A.
  -   `d(A).right(B)`, selects B on the right side of A.
  -   `d(A).up(B)`, selects B above A.
  -   `d(A).down(B)`, selects B under A.

  So for above cases, we can alternatively select it with:

  ```python
  ## select "switch" on the right side of "Wi‑Fi"
  d(text="Wi‑Fi").right(className="android.widget.Switch").click()
  ```

* Multiple instances

  Sometimes the screen may contain multiple views with the same properties, e.g. text, then you will
  have to use the "instance" property in the selector to pick one of qualifying instances, like below:

  ```python
  d(text="Add new", instance=0)  # which means the first instance with text "Add new"
  ```

  In addition, uiautomator2 provides a list-like API (similar to jQuery):

  ```python
  # get the count of views with text "Add new" on current screen
  d(text="Add new").count

  # same as count property
  len(d(text="Add new"))

  # get the instance via index
  d(text="Add new")[0]
  d(text="Add new")[1]
  ...

  # iterator
  for view in d(text="Add new"):
      view.info  # ...
  ```

  **Notes**: when using selectors in a code block that walk through the result list, you must ensure that the UI elements on the screen
  keep unchanged. Otherwise, when Element-Not-Found error could occur when iterating through the list.

#### Get the selected ui object status and its information
* Check if the specific UI object exists

    ```python
    d(text="Settings").exists # True if exists, else False
    d.exists(text="Settings") # alias of above property.

    # advanced usage
    d(text="Settings").exists(timeout=3) # wait Settings appear in 3s, same as .wait(3)
    ```

* Retrieve the info of the specific UI object

    ```python
    d(text="Settings").info
    ```

    Below is a possible output:

    ```
    { u'contentDescription': u'',
    u'checked': False,
    u'scrollable': False,
    u'text': u'Settings',
    u'packageName': u'com.android.launcher',
    u'selected': False,
    u'enabled': True,
    u'bounds': {u'top': 385,
                u'right': 360,
                u'bottom': 585,
                u'left': 200},
    u'className': u'android.widget.TextView',
    u'focused': False,
    u'focusable': True,
    u'clickable': True,
    u'chileCount': 0,
    u'longClickable': True,
    u'visibleBounds': {u'top': 385,
                        u'right': 360,
                        u'bottom': 585,
                        u'left': 200},
    u'checkable': False
    }
    ```

* Get/Set/Clear text of an editable field (e.g., EditText widgets)

    ```python
    d(text="Settings").get_text()  # get widget text
    d(text="Settings").set_text("My text...")  # set the text
    d(text="Settings").clear_text()  # clear the text
    ```

* Get Widget center point

    ```python
    x, y = d(text="Settings").center()
    # x, y = d(text="Settings").center(offset=(0, 0)) # left-top x, y
    ```
    
* Take screenshot of widget

    ```python
    im = d(text="Settings").screenshot()
    im.save("settings.jpg")
    ```

#### Perform the click action on the selected UI object
* Perform click on the specific   object

    ```python
    # click on the center of the specific ui object
    d(text="Settings").click()
    
    # wait element to appear for at most 10 seconds and then click
    d(text="Settings").click(timeout=10)
    
    # click with offset(x_offset, y_offset)
    # click_x = x_offset * width + x_left_top
    # click_y = y_offset * height + y_left_top
    d(text="Settings").click(offset=(0.5, 0.5)) # Default center
    d(text="Settings").click(offset=(0, 0)) # click left-top
    d(text="Settings").click(offset=(1, 1)) # click right-bottom

    # click when exists in 10s, default timeout 0s
    clicked = d(text='Skip').click_exists(timeout=10.0)
    
    # click until element gone, return bool
    is_gone = d(text="Skip").click_gone(maxretry=10, interval=1.0) # maxretry default 10, interval default 1.0
    ```

* Perform long click on the specific UI object

    ```python
    # long click on the center of the specific UI object
    d(text="Settings").long_click()
    ```

#### Gesture actions for the specific UI object
* Drag the UI object towards another point or another UI object 

    ```python
    # notes : drag can not be used for Android<4.3.
    # drag the UI object to a screen point (x, y), in 0.5 second
    d(text="Settings").drag_to(x, y, duration=0.5)
    # drag the UI object to (the center position of) another UI object, in 0.25 second
    d(text="Settings").drag_to(text="Clock", duration=0.25)
    ```

* Swipe from the center of the UI object to its edge

    Swipe supports 4 directions:

    - left
    - right
    - top
    - bottom

    ```python
    d(text="Settings").swipe("right")
    d(text="Settings").swipe("left", steps=10)
    d(text="Settings").swipe("up", steps=20) # 1 steps is about 5ms, so 20 steps is about 0.1s
    d(text="Settings").swipe("down", steps=20)
    ```

* Two-point gesture from one point to another

  ```python
  d(text="Settings").gesture((sx1, sy1), (sx2, sy2), (ex1, ey1), (ex2, ey2))
  ```

* Two-point gesture on the specific UI object

  Supports two gestures:
  - `In`, from edge to center
  - `Out`, from center to edge

  ```python
  # notes : pinch can not be set until Android 4.3.
  # from edge to center. here is "In" not "in"
  d(text="Settings").pinch_in(percent=100, steps=10)
  # from center to edge
  d(text="Settings").pinch_out()
  ```

* Wait until the specific UI appears or disappears
    
    ```python
    # wait until the ui object appears
    d(text="Settings").wait(timeout=3.0) # return bool
    # wait until the ui object gone
    d(text="Settings").wait_gone(timeout=1.0)
    ```

    The default timeout is 20s. see **global settings** for more details

* Perform fling on the specific ui object(scrollable)

  Possible properties:
  - `horiz` or `vert`
  - `forward` or `backward` or `toBeginning` or `toEnd`

  ```python
  # fling forward(default) vertically(default) 
  d(scrollable=True).fling()
  # fling forward horizontally
  d(scrollable=True).fling.horiz.forward()
  # fling backward vertically
  d(scrollable=True).fling.vert.backward()
  # fling to beginning horizontally
  d(scrollable=True).fling.horiz.toBeginning(max_swipes=1000)
  # fling to end vertically
  d(scrollable=True).fling.toEnd()
  ```

* Perform scroll on the specific ui object(scrollable)

  Possible properties:
  - `horiz` or `vert`
  - `forward` or `backward` or `toBeginning` or `toEnd`, or `to`

  ```python
  # scroll forward(default) vertically(default)
  d(scrollable=True).scroll(steps=10)
  # scroll forward horizontally
  d(scrollable=True).scroll.horiz.forward(steps=100)
  # scroll backward vertically
  d(scrollable=True).scroll.vert.backward()
  # scroll to beginning horizontally
  d(scrollable=True).scroll.horiz.toBeginning(steps=100, max_swipes=1000)
  # scroll to end vertically
  d(scrollable=True).scroll.toEnd()
  # scroll forward vertically until specific ui object appears
  d(scrollable=True).scroll.to(text="Security")
  ```

### WatchContext
目前的这个watch_context是用threading启动的,每2s检查一次
目前还只有click这一种触发操作

```python
with d.watch_context() as ctx:
    # 当同时出现 (立即下载 或 立即更新)和 取消 按钮的时候,点击取消
    ctx.when("^立即(下载|更新)").when("取消").click() 
    ctx.when("同意").click()
    ctx.when("确定").click()
    # 上面三行代码是立即执行完的,不会有什么等待
    
    ctx.wait_stable() # 开启弹窗监控,并等待界面稳定(两个弹窗检查周期内没有弹窗代表稳定)

    # 使用call函数来触发函数回调
    # call 支持两个参数,d和el,不区分参数位置,可以不传参,如果传参变量名不能写错
    # eg: 当有元素匹配仲夏之夜,点击返回按钮
    ctx.when("仲夏之夜").call(lambda d: d.press("back"))
    ctx.when("确定").call(lambda el: el.click())

    # 其他操作

# 为了方便也可以使用代码中默认的弹窗监控逻辑
# 下面是目前内置的默认逻辑,可以加群at群主,增加新的逻辑,或者直接提pr
    # when("继续使用").click()
    # when("移入管控").when("取消").click()
    # when("^立即(下载|更新)").when("取消").click()
    # when("同意").click()
    # when("^(好的|确定)").click()
with d.watch_context(builtin=True) as ctx:
    # 在已有的基础上增加
    ctx.when("@tb:id/jview_view").when('//*[@content-desc="图片"]').click()

    # 其他脚本逻辑
```

另外一种写法

```python
ctx = d.watch_context()
ctx.when("设置").click()
ctx.wait_stable() # 等待界面不在有弹窗了

ctx.close()
```

### Watcher
**更推荐用WatchContext** 写法更简洁一些

~~You can register [watchers](http://developer.android.com/tools/help/uiautomator/UiWatcher.html) to perform some actions when a selector does not find a match.~~

2.0.0之前使用的是 uiautomator-jar库中提供的[Watcher]((http://developer.android.com/tools/help/uiautomator/UiWatcher.html)方法,但在实践中发现一旦uiautomator连接失败重启了,所有的watcher配置都是丢失,这肯定是无法接受的。

所以目前采用了后台运行了一个线程的方法(依赖threading库),然后每隔一段时间dump一次hierarchy,匹配到元素之后执行相应的操作。

用法举例

注册监控

```python
# 常用写法,注册匿名监控
d.watcher.when("安装").click()

# 注册名为ANR的监控,当出现ANR和Force Close时,点击Force Close
d.watcher("ANR").when(xpath="ANR").when("Force Close").click()

# 其他回调例子
d.watcher.when("抢红包").press("back")
d.watcher.when("//*[@text = 'Out of memory']").call(lambda d: d.shell('am force-stop com.im.qq'))

# 回调说明
def click_callback(d: u2.Device):
    d.xpath("确定").click() # 在回调中调用不会再次触发watcher

d.xpath("继续").click() # 使用d.xpath检查元素的时候,会触发watcher(目前最多触发5次)

# 开始后台监控
d.watcher.start()
```

监控操作

```python
# 移除ANR的监控
d.watcher.remove("ANR")

# 移除所有的监控
d.watcher.remove()

# 开始后台监控
d.watcher.start()
d.watcher.start(2.0) # 默认监控间隔2.0s

# 强制运行所有监控
d.watcher.run()

# 停止监控
d.watcher.stop()

# 停止并移除所有的监控,常用于初始化
d.watcher.reset()
```

另外文档还是有很多没有写,推荐直接去看源码[watcher.py](uiautomator2/watcher.py)

### Global settings

```python
u2.HTTP_TIMEOUT = 60 # 默认值60s, http默认请求超时时间
```

其他的配置,目前已大部分集中到 `d.settings` 中,根据后期的需求配置可能会有增减。

```python
print(d.settings)
{'operation_delay': (0, 0),
 'operation_delay_methods': ['click', 'swipe'],
 'wait_timeout': 20.0}

# 配置点击前延时0.5s,点击后延时1s
d.settings['operation_delay'] = (.5, 1)

# 修改延迟生效的方法
# 其中 double_click, long_click 都对应click
d.settings['operation_delay_methods'] = ['click', 'swipe', 'drag', 'press']
d.settings['wait_timeout'] = 20.0 # 默认控件等待时间(原生操作,xpath插件的等待时间)

d.settings['max_depth'] = 50 # 默认50,限制dump_hierarchy返回的元素层级
```

对于随着版本升级,设置过期的配置时,会提示Deprecated,但是不会抛异常。

```bash
>>> d.settings['click_before_delay'] = 1  
[W 200514 14:55:59 settings:72] d.settings[click_before_delay] deprecated: Use operation_delay instead
```

**uiautomator恢复方式设置**

细心的你可能发现,实际上手机安装了两个APK,一个在前台可见(小黄车)。一个包名为`com.github.uiautomator.test`在后台不可见。这两个apk使用同一个证书签名的。
不可见的应用实际上是一个测试包,包含有所有的测试代码,核心的测试服务也是通过其启动的。
但是运行的时候,系统却需要那个小黄车一直在运行(在后台运行也可以)。一旦小黄车应用被杀,后台运行的测试服务也很快的会被杀掉。就算什么也不做,应用应用在后台,也会很快被系统回收掉。(这里希望高手指点一下,如何才能不依赖小黄车应用,感觉理论上是可以的,但是目前我还不会)。

~~让小黄车在后台运行有两种方式,一种启动应用后,放到后台(默认)。另外通过`am startservice`启动一个后台服务也行。~~

~~通过 `d.settings["uiautomator_runtest_app_background"] = True` 可以调整该行为。True代表启动应用,False代表启动服务。~~

UiAutomator中的超时设置(隐藏方法)

```python
>> d.jsonrpc.getConfigurator() 
{'actionAcknowledgmentTimeout': 500,
 'keyInjectionDelay': 0,
 'scrollAcknowledgmentTimeout': 200,
 'waitForIdleTimeout': 0,
 'waitForSelectorTimeout': 0}

>> d.jsonrpc.setConfigurator({"waitForIdleTimeout": 100})
{'actionAcknowledgmentTimeout': 500,
 'keyInjectionDelay': 0,
 'scrollAcknowledgmentTimeout': 200,
 'waitForIdleTimeout': 100,
 'waitForSelectorTimeout': 0}
```

为了防止客户端程序响应超时,`waitForIdleTimeout`和`waitForSelectorTimeout`目前已改为`0`

Refs: [Google uiautomator Configurator](https://developer.android.com/reference/android/support/test/uiautomator/Configurator)

### Input method
这种方法通常用于不知道控件的情况下的输入。

```python
# 目前采用从剪贴板粘贴的方式输入
d.send_keys("你好123abcEFG")
d.send_keys("你好123abcEFG", clear=True)

d.clear_text() # 清除输入框所有内容

d.send_action() # 根据输入框的需求,自动执行回车、搜索等指令, Added in version 3.1
# 也可以指定发送的输入法action, eg: d.send_action("search") 支持 go, search, send, next, done, previous
```



```python
print(d.current_ime()) # 获取当前输入法ID

```

> 更多参考: [IME_ACTION_CODE](https://developer.android.com/reference/android/view/inputmethod/EditorInfo)

### Toast
```python
print(d.last_toast) # get last toast, if not toast return None
d.clear_toast()
```

> Fixed in version 3.2.0

### XPath
Java uiautoamtor中默认是不支持xpath的,所以这里属于扩展的一个功能。速度不是这么的快。

For example: 其中一个节点的内容

```xml
<android.widget.TextView
  index="2"
  text="05:19"
  resource-id="com.netease.cloudmusic:id/qf"
  package="com.netease.cloudmusic"
  content-desc=""
  checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false"
  scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true"
  bounds="[957,1602][1020,1636]" />
```

xpath定位和使用方法

有些属性的名字有修改需要注意

```
description -> content-desc
resourceId -> resource-id
```

常见用法

```python
# wait exists 10s
d.xpath("//android.widget.TextView").wait(10.0)
# find and click
d.xpath("//*[@content-desc='分享']").click()
# check exists
if d.xpath("//android.widget.TextView[contains(@text, 'Se')]").exists:
    print("exists")
# get all text-view text, attrib and center point
for elem in d.xpath("//android.widget.TextView").all():
    print("Text:", elem.text)
    # Dictionary eg: 
    # {'index': '1', 'text': '999+', 'resource-id': 'com.netease.cloudmusic:id/qb', 'package': 'com.netease.cloudmusic', 'content-desc': '', 'checkable': 'false', 'checked': 'false', 'clickable': 'false', 'enabled': 'true', 'focusable': 'false', 'focused': 'false','scrollable': 'false', 'long-clickable': 'false', 'password': 'false', 'selected': 'false', 'visible-to-user': 'true', 'bounds': '[661,1444][718,1478]'}
    print("Attrib:", elem.attrib)
    # Coordinate eg: (100, 200)
    print("Position:", elem.center())
```

点击查看[其他XPath常见用法](XPATH.md)

### Screenrecord (Deprecated)
视频录制(废弃),使用[scrcpy](https://github.com/Genymobile/scrcpy)来代替吧

这里没有使用手机中自带的screenrecord命令,是通过获取手机图片合成视频的方法,所以需要安装一些其他的依赖,如imageio, imageio-ffmpeg, numpy等
因为有些依赖比较大,推荐使用镜像安装。直接运行下面的命令即可。

```bash
pip3 install -U "uiautomator2[image]" -i https://pypi.doubanio.com/simple
```

使用方法

```
d.screenrecord('output.mp4')

time.sleep(10)
# or do something else

d.screenrecord.stop() # 停止录制后,output.mp4文件才能打开
```

录制的时候也可以指定fps(当前是20),这个值是率低于minicap输出图片的速度,感觉已经很好了,不建议你修改。

# Enable uiautomator2 logger

```python
from uiautomator2 import enable_pretty_logging
enable_pretty_logging()
```

Or

```
logger = logging.getLogger("uiautomator2")
# setup logger
```

## Stop UiAutomator
Python程序退出了,UiAutomation就退出了。
不过也可以通过接口的方法停止服务

```python
d.stop_uiautomator()
```

## Google UiAutomator 2.0和1.x的区别
https://www.cnblogs.com/insist8089/p/6898181.html

- 新增接口:UiObject2、Until、By、BySelector
- 引入方式:2.0中,com.android.uiautomator.core.* 引入方式被废弃。改为android.support.test.uiautomator
- 构建系统:Maven 和/或 Ant(1.x);Gradle(2.0)
- 产生的测试包的形式:从zip /jar(1.x) 到 apk(2.0)
- 在本地环境以adb命令运行UIAutomator测试,启动方式的差别:   
  adb shell uiautomator runtest UiTest.jar -c package.name.ClassName(1.x)
  adb shell am instrument -e class com.example.app.MyTest 
  com.example.app.test/android.support.test.runner.AndroidJUnitRunner(2.0)
- 能否使用Android服务及接口? 1.x~不能;2.0~能。
- og输出? 使用System.out.print输出流回显至执行端(1.x); 输出至Logcat(2.0)
- 执行?测试用例无需继承于任何父类,方法名不限,使用注解 Annotation进行(2.0);  需要继承UiAutomatorTestCase,测试方法需要以test开头(1.x) 


## 依赖项目
- uiautomator jsonrpc server<https://github.com/openatx/android-uiautomator-server/>
- ~~uiautomator守护程序 <https://github.com/openatx/atx-agent>~~

# Contributors
- codeskyblue ([@codeskyblue][])
- Xiaocong He ([@xiaocong][])
- Yuanyuan Zou ([@yuanyuan][])
- Qian Jin ([@QianJin2013][])
- Xu Jingjie ([@xiscoxu][])
- Xia Mingyuan ([@mingyuan-xia][])
- Artem Iglikov, Google Inc. ([@artikz][])

[@codeskyblue]: https://github.com/codeskyblue
[@xiaocong]: https://github.com/xiaocong
[@yuanyuan]: https://github.com/yuanyuanzou
[@QianJin2013]: https://github.com/QianJin2013
[@xiscoxu]: https://github.com/xiscoxu
[@mingyuan-xia]: https://github.com/mingyuan-xia
[@artikz]: https://github.com/artikz

Other [contributors](../../graphs/contributors)

## 其他优秀的项目
- https://github.com/atinfo/awesome-test-automation 所有优秀测试框架的集合,包罗万象
- [google/mobly](https://github.com/google/mobly) 谷歌内部的测试框架,虽然我不太懂,但是感觉很好用
- https://github.com/zhangzhao4444/Maxim 基于Uiautomator的monkey
- http://www.sikulix.com/ 基于图像识别的自动化测试框架,非常的老牌
- http://airtest.netease.com/ 本项目的前身,后来被网易广州团队接手并继续优化。实现有一个不错的IDE

排名有先后,欢迎补充

# LICENSE
[MIT](LICENSE)


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/openatx/uiautomator2",
    "name": "uiautomator2",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "codeskyblue",
    "author_email": "codeskyblue@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/b8/92/746aba119f556334719e0d1d9eef71c9646729585f0f9ee88567364041e9/uiautomator2-3.2.8.tar.gz",
    "platform": null,
    "description": "# uiautomator2\n[![PyPI](https://img.shields.io/pypi/v/uiautomator2.svg)](https://pypi.python.org/pypi/uiautomator2)\n![PyPI](https://img.shields.io/pypi/pyversions/uiautomator2.svg)\n[![codecov](https://codecov.io/gh/openatx/uiautomator2/graph/badge.svg?token=d0ZLkqorBu)](https://codecov.io/gh/openatx/uiautomator2)\n\nQQ\u4ea4\u6d41\u7fa4: **815453846**\nDiscord: <https://discord.gg/PbJhnZJKDd>\n\n> \u6709\u6bb5\u65f6\u95f4\u6ca1\u6709\u7ef4\u62a4\u8fd9\u4e2a\u9879\u76ee\u4e86\uff08\u53ef\u80fd\u6709\u4e24\u5e74\u4e86\uff09\uff0c\u4f46\u662f\u6700\u8fd1\u5de5\u4f5c\u9700\u8981\u53c8\u91cd\u65b0\u7814\u7a76\u4e00\u4e0bAndroid\u539f\u751f\u81ea\u52a8\u5316\uff0c\u5f53\u7136\u53c8\u8c03\u7814\u4e86Appium\uff0c\u5bf9\u6bd4\u4e0b\u6765\u4e00\u770b\uff0c\u53d1\u73b0uiautomator2\u8fd9\u4e2a\u9879\u76ee\u7684\u8fd0\u884c\u901f\u5ea6\u662f\u771f\u7684\u597d\u5feb\uff0c\u4ece\u68c0\u6d4b\u5143\u7d20\u5230\u70b9\u51fb\uff0c\u90fd\u662f\u6beb\u79d2\u7ea7\u7684\uff0c\u4ee3\u7801\u4e5f\u6bd4\u8f83\u597d\u7406\u89e3\u3002\u771f\u662f\u6ca1\u60f3\u5230\u4ee5\u524d\u7adf\u7136\u5199\u51fa\u4e86\u8fd9\u4e48\u795e\u5947\u7684\u9879\u76ee\uff0c\u8fd9\u4e48\u597d\u7684\u9879\u76ee\u600e\u4e48\u80fd\u8ba9\u5b83\u843d\u7070\u5462\uff0c\u5f97\u597d\u597d\u6574\u4e00\u6574\uff0c\u4e00\u4e9b\u5783\u573e\u4ee3\u7801\u6e05\u7406\u6e05\u7406\u3002\u6240\u4ee5\u9879\u76ee\u7248\u672c\u4ece2.x.x\u5347\u7ea7\u5230\u4e863.x.x\n\n\u8fd8\u5728\u75282.x.x\u7248\u672c\u7684\u7528\u6237\uff0c\u53ef\u4ee5\u5148\u770b\u4e00\u4e0b[2to3](docs/2to3.md) \u518d\u51b3\u5b9a\u662f\u5426\u8981\u5347\u7ea73.x.x \uff08\u6211\u4e2a\u4eba\u8fd8\u662f\u975e\u5e38\u5efa\u8bae\u5347\u7ea7\u7684\uff09\n\n2\u52303\u6bd5\u7adf\u662f\u5927\u7248\u672c\u5347\u7ea7\uff0c\u5f88\u591a\u7684\u51fd\u6570\u5220\u6389\u4e86\u3002\u9996\u5148\u5220\u6389\u7684\u5c31\u662fatx-agent\uff0c\u5176\u6b21\u8fd8\u6709\u4e00\u5806atx-agent\u76f8\u5173\u7684\u51fd\u6570\u3002\u5e9f\u5f03\u7684\u529f\u80fd\u6bd4\u5982init.\n\n\u5404\u79cd\u4f9d\u8d56\u5e93\u7684\u7248\u672c\u53f7\n\n- [![PyPI](https://img.shields.io/pypi/v/uiautomator2.svg?label=uiautomator2)](https://pypi.python.org/pypi/uiautomator2)\n- [![PyPI](https://img.shields.io/pypi/v/adbutils.svg?label=adbutils)](https://github.com/openatx/adbutils)\n- [![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/openatx/android-uiautomator-server.svg?label=android-uiautomator-server)](https://github.com/openatx/android-uiautomator-server)\n- ~~[![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/openatx/atx-agent.svg?label=atx-agent)](https://github.com/openatx/atx-agent)~~\n\n[UiAutomator](https://developer.android.com/training/testing/ui-automator.html)\u662fGoogle\u63d0\u4f9b\u7684\u7528\u6765\u505a\u5b89\u5353\u81ea\u52a8\u5316\u6d4b\u8bd5\u7684\u4e00\u4e2aJava\u5e93\uff0c\u57fa\u4e8eAccessibility\u670d\u52a1\u3002\u529f\u80fd\u5f88\u5f3a\uff0c\u53ef\u4ee5\u5bf9\u7b2c\u4e09\u65b9App\u8fdb\u884c\u6d4b\u8bd5\uff0c\u83b7\u53d6\u5c4f\u5e55\u4e0a\u4efb\u610f\u4e00\u4e2aAPP\u7684\u4efb\u610f\u4e00\u4e2a\u63a7\u4ef6\u5c5e\u6027\uff0c\u5e76\u5bf9\u5176\u8fdb\u884c\u4efb\u610f\u64cd\u4f5c\uff0c\u4f46\u6709\u4e24\u4e2a\u7f3a\u70b9\uff1a1. \u6d4b\u8bd5\u811a\u672c\u53ea\u80fd\u4f7f\u7528Java\u8bed\u8a00 2. \u6d4b\u8bd5\u811a\u672c\u8981\u6253\u5305\u6210jar\u6216\u8005apk\u5305\u4e0a\u4f20\u5230\u8bbe\u5907\u4e0a\u624d\u80fd\u8fd0\u884c\u3002\n\n\u6211\u4eec\u5e0c\u671b\u6d4b\u8bd5\u903b\u8f91\u80fd\u591f\u7528Python\u7f16\u5199\uff0c\u80fd\u591f\u5728\u7535\u8111\u4e0a\u8fd0\u884c\u7684\u65f6\u5019\u5c31\u63a7\u5236\u624b\u673a\u3002\u8fd9\u91cc\u8981\u975e\u5e38\u611f\u8c22 Xiaocong He ([@xiaocong][])\uff0c\u4ed6\u5c06\u8fd9\u4e2a\u60f3\u6cd5\u5b9e\u73b0\u4e86\u51fa\u6765\uff08\u89c1[xiaocong/uiautomator](https://github.com/xiaocong/uiautomator)\uff09\uff0c\u539f\u7406\u662f\u5728\u624b\u673a\u4e0a\u8fd0\u884c\u4e86\u4e00\u4e2ahttp rpc\u670d\u52a1\uff0c\u5c06uiautomator\u4e2d\u7684\u529f\u80fd\u5f00\u653e\u51fa\u6765\uff0c\u7136\u540e\u518d\u5c06\u8fd9\u4e9bhttp\u63a5\u53e3\u5c01\u88c5\u6210Python\u5e93\u3002\n\u56e0\u4e3a`xiaocong/uiautomator`\u8fd9\u4e2a\u5e93\uff0c\u5df2\u7ecf\u5f88\u4e45\u4e0d\u89c1\u66f4\u65b0\u3002\u6240\u4ee5\u6211\u4eec\u76f4\u63a5fork\u4e86\u4e00\u4e2a\u7248\u672c\uff0c\u4e3a\u4e86\u65b9\u4fbf\u505a\u533a\u5206\u6211\u4eec\u5c31\u5728\u540e\u9762\u52a0\u4e86\u4e2a2 [openatx/uiautomator2](https://github.com/openatx/uiautomator2),\u5bf9\u5e94\u7684Android\u5305\u6e90\u7801\u6211\u4e5ffork\u4e86\u4e00\u4efd\uff0c[openatx/android-uiautomator-server](https://github.com/openatx/android-uiautomator-server)\n\n\u9664\u4e86\u5bf9\u539f\u6709\u7684\u5e93\u7684bug\u8fdb\u884c\u4e86\u4fee\u590d\uff0c\u8fd8\u589e\u52a0\u4e86\u5f88\u591a\u65b0\u7684Feature\u3002\u4e3b\u8981\u6709\u4ee5\u4e0b\u90e8\u5206\uff1a\n\n* ~~\u8bbe\u5907\u548c\u5f00\u53d1\u673a\u53ef\u4ee5\u8131\u79bb\u6570\u636e\u7ebf\uff0c\u901a\u8fc7WiFi\u4e92\u8054\uff08\u57fa\u4e8e[atx-agent](https://github.com/openatx/atx-agent)~~\n* ~~\u96c6\u6210\u4e86[openstf/minicap](https://github.com/openstf/minicap)\u8fbe\u5230\u5b9e\u65f6\u5c4f\u5e55\u6295\u9891\uff0c\u4ee5\u53ca\u5b9e\u65f6\u622a\u56fe~~\n* ~~\u96c6\u6210\u4e86[openstf/minitouch](https://github.com/openstf/minitouch)\u8fbe\u5230\u7cbe\u786e\u5b9e\u65f6\u63a7\u5236\u8bbe\u5907~~\n* \u4fee\u590d\u4e86[xiaocong/uiautomator](https://github.com/xiaocong/uiautomator)\u7ecf\u5e38\u6027\u9000\u51fa\u7684\u95ee\u9898\n* \u4ee3\u7801\u8fdb\u884c\u4e86\u91cd\u6784\u548c\u7cbe\u7b80\uff0c\u65b9\u4fbf\u7ef4\u62a4\n* \u5b9e\u73b0\u4e86\u4e00\u4e2a\u8bbe\u5907\u7ba1\u7406\u5e73\u53f0(\u4e5f\u652f\u6301iOS) [atxserver2](https://github.com/openatx/atxserver2) \uff08\u6ce8\uff1a\u76ee\u524d\u4e0d\u600e\u4e48\u7ef4\u62a4\u4e86\uff09\n* \u6269\u5145\u4e86toast\u83b7\u53d6\u548c\u5c55\u793a\u7684\u529f\u80fd\uff08\u9700\u8981\u624b\u52a8\u5f00\u542fATX\u7684\u60ac\u6d6e\u7a97\u6743\u9650\uff09 \u8c8c\u4f3c\u6709bug\u7528\u4e0d\u4e86\n\n>\u8fd9\u91cc\u8981\u5148\u8bf4\u660e\u4e0b\uff0c\u56e0\u4e3a\u7ecf\u5e38\u6709\u5f88\u591a\u4eba\u95ee openatx/uiautomator2 \u5e76\u4e0d\u652f\u6301iOS\u6d4b\u8bd5\uff0c\u9700\u8981iOS\u81ea\u52a8\u5316\u6d4b\u8bd5\uff0c\u53ef\u4ee5\u8f6c\u5230\u8fd9\u4e2a\u5e93 [openatx/facebook-wda](https://github.com/openatx/facebook-wda)\u3002\n\n> PS: \u8fd9\u4e2a\u5e93 ~~<https://github.com/NeteaseGame/ATX>~~ \u76ee\u524d\u5df2\u7ecf\u4e0d\u7ef4\u62a4\u4e86\uff0c\u8bf7\u5c3d\u5feb\u66f4\u6362\u3002\n\n\u8fd9\u91cc\u6709\u4e00\u4efd\u5feb\u901f\u53c2\u8003\uff0c\u9002\u5408\u5df2\u7ecf\u5165\u95e8\u7684\u4eba [QUICK REFERENCE GUIDE](QUICK_REFERENCE.md)\uff0c\u6b22\u8fce\u591a\u63d0\u610f\u89c1\u3002\n\n## Requirements\n- Android\u7248\u672c 4.4+\n- Python 3.8+\n\n## QUICK START\n\u5148\u51c6\u5907\u4e00\u53f0\uff08\u4e0d\u8981\u4e24\u53f0\uff09\u5f00\u542f\u4e86`\u5f00\u53d1\u8005\u9009\u9879`\u7684\u5b89\u5353\u624b\u673a\uff0c\u8fde\u63a5\u4e0a\u7535\u8111\uff0c\u786e\u4fdd\u6267\u884c`adb devices`\u53ef\u4ee5\u770b\u5230\u8fde\u63a5\u4e0a\u7684\u8bbe\u5907\u3002\n\n\u8fd0\u884c`pip3 install -U uiautomator2` \u5b89\u88c5uiautomator2\n\n\u547d\u4ee4\u884c\u8fd0\u884c`python`\u6253\u5f00python\u4ea4\u4e92\u7a97\u53e3\u3002\u7136\u540e\u5c06\u4e0b\u9762\u7684\u547d\u4ee4\u8f93\u5165\u5230\u7a97\u53e3\u4e2d\u3002\n\n```python\nimport uiautomator2 as u2\n\nd = u2.connect() # connect to device\nprint(d.info)\n```\n\n\u8fd9\u65f6\u770b\u5230\u7c7b\u4f3c\u4e0b\u9762\u7684\u8f93\u51fa\uff0c\u5c31\u53ef\u4ee5\u6b63\u5f0f\u5f00\u59cb\u7528\u6211\u4eec\u8fd9\u4e2a\u5e93\u4e86\u3002\u56e0\u4e3a\u8fd9\u4e2a\u5e93\u529f\u80fd\u592a\u591a\uff0c\u540e\u9762\u8fd8\u6709\u5f88\u591a\u7684\u5185\u5bb9\uff0c\u9700\u8981\u6162\u6162\u53bb\u770b ....\n\n```\n{'currentPackageName': 'net.oneplus.launcher', 'displayHeight': 1920, 'displayRotation': 0, 'displaySizeDpX': 411, 'displaySizeDpY': 731, 'displayWidth': 1080, 'productName': 'OnePlus5', '\nscreenOn': True, 'sdkInt': 27, 'naturalOrientation': True}\n```\n\n\u53e6\u5916\u4e3a\u4e86\u4fdd\u6301\u7a33\u5b9a\uff0c\u8fd8\u9700\u8981\u5f00\u542f`\u5c0f\u9ec4\u8f66`\u7684\u60ac\u6d6e\u7a97\u6743\u9650\u3002\u53c2\u8003\u6587\u7ae0 [py-uiautomator2\u901a\u8fc7\u60ac\u6d6e\u7a97\u8ba9\u670d\u52a1\u957f\u65f6\u95f4\u53ef\u7528](https://zhuanlan.zhihu.com/p/688009468)\n\n\u4e00\u822c\u60c5\u51b5\u4e0b\u90fd\u4f1a\u6210\u529f\uff0c\u4e0d\u8fc7\u4e5f\u53ef\u80fd\u4f1a\u6709\u610f\u5916\u3002\u53ef\u4ee5\u52a0QQ\u7fa4\u53cd\u9988\u95ee\u9898(\u7fa4\u53f7\u5728\u6700\u4e0a\u9762\uff09\uff0c\u7fa4\u91cc\u6709\u5f88\u591a\u5927\u4f6c\u53ef\u4ee5\u5e2e\u4f60\u89e3\u51b3\u95ee\u9898\u3002\n\n## Sponsors\nThank you to all our sponsors! \u2728\ud83c\udf70\u2728\n\n### \u91d1\u724c\u8d5e\u52a9\u5546\uff08Gold Sponsor\uff09\nEmpty\n\n# Article Recommended\n\u4f18\u79c0\u6587\u7ae0\u63a8\u8350 (\u6b22\u8fceQQ\u7fa4\u91ccat\u6211\u53cd\u9988\uff09\n\n- [termux\u91cc\u5982\u4f55\u90e8\u7f72uiautomator2\u7b80\u4ecb](https://www.cnblogs.com/ze-yan/p/12242383.html) by `\u6210\u90fd-\u6d4b\u8bd5\u53ea\u4f1a\u4e00\u70b9\u70b9`\n\n## \u76f8\u5173\u9879\u76ee\n- \u57fa\u4e8eadb\u534f\u8bae\u4e0eAndroid\u8fdb\u884c\u4ea4\u4e92\u7684\u5e93 [adbutils](https://github.com/openatx/adbutils)\n- [uiauto.dev](https://uiauto.dev) \u7528\u4e8e\u67e5\u770bUI\u5c42\u7ea7\u7ed3\u6784\uff0c\u7c7b\u4f3c\u4e8euiautomatorviewer(\u7528\u4e8e\u66ff\u4ee3\u4e4b\u524d\u5199\u7684weditor\uff09\uff0c\u7528\u4e8e\u67e5\u770bUI\u5c42\u7ea7\u7ed3\u6784 \n- \u8bbe\u5907\u7ba1\u7406\u5e73\u53f0\uff0c\u8bbe\u5907\u591a\u4e86\u5c31\u4f1a\u7528\u5230 [atxserver2](https://github.com/openatx/atxserver2) \uff08\u5bfb\u627e\u9879\u76ee\u7ef4\u62a4\u4eba\u5458\uff09\n- ~~[atx-agent](https://github.com/openatx/atx-agent) \u8fd0\u884c\u5728\u8bbe\u5907\u4e0a\u7684\u9a7b\u5b88\u7a0b\u5e8f\uff0cgo\u5f00\u53d1\uff0c\u7528\u4e8e\u4fdd\u6d3b\u8bbe\u5907\u4e0a\u76f8\u5173\u7684\u670d\u52a1~~\n- ~~[weditor](https://github.com/openatx/weditor) \u7c7b\u4f3c\u4e8euiautomatorviewer\uff0c\u4e13\u95e8\u4e3a\u672c\u9879\u76ee\u5f00\u53d1\u7684\u8f85\u52a9\u7f16\u8f91\u5668(\u8fd9\u4e2a\u6682\u4e0d\u7ef4\u62a4\u4e86~~\n\n**[Installation](#installation)**\n\n**[Connect to a device](#connect-to-a-device)**\n\n**[Command line](#command-line)**\n\n**[Global settings](#global-settings)**\n  - **[Debug HTTP requests](#debug-http-requests)**\n  - **[Implicit wait](#implicit-wait)**\n\n**[App management](#app-management)**\n  - **[Install an app](#install-an-app)**\n  - **[Launch an app](#launch-an-app)**\n  - **[Stop an app](#stop-an-app)**\n  - **[Stop all running apps](#stop-all-running-apps)**\n  - **[Push and pull files](#push-and-pull-files)**\n  - **[Other app operations](#other-app-operations)**\n\n**[UI automation](#basic-api-usages)**\n  - **[Shell commands](#shell-commands)**\n  - **[Session](#session)**\n  - **[Retrieve the device info](#retrieve-the-device-info)**\n  - **[Key Events](#key-events)**\n  - **[Gesture interaction with the device](#gesture-interaction-with-the-device)**\n  - **[Screen-related](#screen-related)**\n  - **[Selector](#selector)**\n  - **[Watcher](#watcher)**\n  - **[Global settings](#global-settings)**\n  - **[Input method](#input-method)**\n  - **[Toast](#toast)**\n  - **[XPath](#xpath)**\n  - **[Screenrecord](#screenrecord)**\n  - **[Image match](#image-match) Removed**\n\n\n**[Contributors](#contributors)**\n\n**[LICENSE](#license)**\n\n\n# Installation\n1. Install uiautomator2\n\n    ```bash\n    pip install -U uiautomator2\n    ```\n    \n    \u6d4b\u8bd5\u662f\u5426\u5b89\u88c5\u6210\u529f `uiautomator2 --help`\n    \n2. UI Inspector\n\n    ```bash\n    pip install uiautodev\n    # \u542f\u52a8\n    uiauto.dev\n    ```\n\n    \u6d4f\u89c8\u5668\u6253\u5f00 https://uiauto.dev \u67e5\u770b\u5f53\u524d\u8bbe\u5907\u7684\u754c\u9762\u7ed3\u6784\u3002\n\n    **uiauto.dev**\n\n    [uiauto.dev](https://github.com/codeskyblue/uiauto.dev) \u662f\u4e00\u4e2a\u72ec\u7acb\u4e0euiautomator2\u4e4b\u5916\u7684\u4e00\u4e2a\u9879\u76ee\uff0c\u7528\u4e8e\u67e5\u770b\u56fe\u5c42\u7ed3\u6784\u7684\u3002\u5c5e\u4e8e\u65e7\u7248\u9879\u76ee[weditor\u7684\u91cd\u6784\u7248\u672c](https://github.com/openatx/weditor)\uff0c\u540e\u7eed\u4e5f\u8bb8\u4f1a\u6536\u8d39\uff08\u4ef7\u683c\u80af\u5b9a\u7269\u8d85\u6240\u503c\uff09\uff0c\u6765\u652f\u6301\u5f53\u524d\u8fd9\u4e2a\u9879\u76ee\u7ee7\u7eed\u7ef4\u62a4\u4e0b\u53bb\u3002\u611f\u5174\u8da3\u7684\u53ef\u4ee5\u52a0\u7fa4\u8ba8\u8bba(\u4e5f\u5305\u542b\u63d0\u9700\u6c42) QQ\u7fa4 536481989\n\n# Connect to a device\nuse serialno to connect device eg. `123456f` (seen from `adb devices`)\n\n```python\nimport uiautomator2 as u2\n\nd = u2.connect('123456f') # alias for u2.connect_usb('123456f')\nprint(d.info)\n```\n\nSerial can be passed through env-var `ANDROID_SERIAL`\n\n\n```python\n# export ANDROID_SERIAL=123456f\nd = u2.connect()\n```\n\n# Command line\n\u5176\u4e2d\u7684`$device_ip`\u4ee3\u8868\u8bbe\u5907\u7684ip\u5730\u5740\n\n\u5982\u9700\u6307\u5b9a\u8bbe\u5907\u9700\u8981\u4f20\u5165`--serial` \u5982 `python3 -m uiautomator2 --serial bff1234 <SubCommand>`, SubCommand\u4e3a\u5b50\u547d\u4ee4\uff08screenshot, current \u7b49\uff09\n\n> 1.0.3 Added: `python3 -m uiautomator2` equals to `uiautomator2`\n\n- screenshot: \u622a\u56fe\n\n    ```bash\n    $ uiautomator2 screenshot screenshot.jpg\n    ```\n\n- current: \u83b7\u53d6\u5f53\u524d\u5305\u540d\u548cactivity\n\n    ```bash\n    $ uiautomator2 current\n    {\n        \"package\": \"com.android.browser\",\n        \"activity\": \"com.uc.browser.InnerUCMobile\",\n        \"pid\": 28478\n    }\n    ```\n    \n- uninstall\uff1a Uninstall app\n\n    ```bash\n    $ uiautomator2 uninstall <package-name> # \u5378\u8f7d\u4e00\u4e2a\u5305\n    $ uiautomator2 uninstall <package-name-1> <package-name-2> # \u5378\u8f7d\u591a\u4e2a\u5305\n    $ uiautomator2 uninstall --all # \u5168\u90e8\u5378\u8f7d\n    ```\n\n- stop: Stop app\n\n    ```bash\n    $ uiautomator2 stop com.example.app # \u505c\u6b62\u4e00\u4e2aapp\n    $ uiautomator2 stop --all # \u505c\u6b62\u6240\u6709\u7684app\n    ```\n\n- doctor:\n\n    ```bash\n    $ uiautomator2 doctor\n    [I 2024-04-25 19:53:36,288 __main__:101 pid:15596] uiautomator2 is OK\n    ```\n    \n# API Documents\n\n### New command timeout \uff08Removed)\nWhen python quit, the UiAutomation service also quit.\n<!-- How long (in seconds) will wait for a new command from the client before assuming the client quit and ending the uiautomator service \uff08Default 3 minutes\uff09\n\n\u914d\u7f6eaccessibility\u670d\u52a1\u7684\u6700\u5927\u7a7a\u95f2\u65f6\u95f4\uff0c\u8d85\u65f6\u5c06\u81ea\u52a8\u91ca\u653e\u3002\u9ed8\u8ba43\u5206\u949f\u3002\n\n```python\nd.set_new_command_timeout(300) # change to 5 minutes, unit seconds\n``` -->\n\n### Debug HTTP requests\n\u6253\u5370\u51fa\u4ee3\u7801\u80cc\u540e\u7684HTTP\u8bf7\u6c42\u4fe1\u606f\n\n```python\n>>> d.debug = True\n>>> d.info\n12:32:47.182 $ curl -X POST -d '{\"jsonrpc\": \"2.0\", \"id\": \"b80d3a488580be1f3e9cb3e926175310\", \"method\": \"deviceInfo\", \"params\": {}}' 'http://127.0.0.1:54179/jsonrpc/0'\n12:32:47.225 Response >>>\n{\"jsonrpc\":\"2.0\",\"id\":\"b80d3a488580be1f3e9cb3e926175310\",\"result\":{\"currentPackageName\":\"com.android.mms\",\"displayHeight\":1920,\"displayRotation\":0,\"displaySizeDpX\":360,\"displaySizeDpY\":640,\"displayWidth\":1080,\"productName\"\n:\"odin\",\"screenOn\":true,\"sdkInt\":25,\"naturalOrientation\":true}}\n<<< END\n```\n\n### Implicit wait\n\u8bbe\u7f6e\u5143\u7d20\u67e5\u627e\u7b49\u5f85\u65f6\u95f4\uff08\u9ed8\u8ba420s\uff09\n\n```python\nd.implicitly_wait(10.0) # \u4e5f\u53ef\u4ee5\u901a\u8fc7d.settings['wait_timeout'] = 10.0 \u4fee\u6539\nd(text=\"Settings\").click() # if Settings button not show in 10s, UiObjectNotFoundError will raised\n\nprint(\"wait timeout\", d.implicitly_wait()) # get default implicit wait\n```\n\nThis function will have influence on `click`, `long_click`, `drag_to`, `get_text`, `set_text`, `clear_text`, etc.\n\n## App management\nThis part showcases how to perform app management\n\n### Install an app\nWe only support installing an APK from a URL\n\n```python\nd.app_install('http://some-domain.com/some.apk')\n```\n\n### Launch an app\n```python\n# \u9ed8\u8ba4\u7684\u8fd9\u79cd\u65b9\u6cd5\u662f\u5148\u901a\u8fc7atx-agent\u89e3\u6790apk\u5305\u7684mainActivity\uff0c\u7136\u540e\u8c03\u7528am start -n $package/$activity\u542f\u52a8\nd.app_start(\"com.example.hello_world\")\n\n# \u4f7f\u7528 monkey -p com.example.hello_world -c android.intent.category.LAUNCHER 1 \u542f\u52a8\n# \u8fd9\u79cd\u65b9\u6cd5\u6709\u4e2a\u526f\u4f5c\u7528\uff0c\u5b83\u81ea\u52a8\u4f1a\u5c06\u624b\u673a\u7684\u65cb\u8f6c\u9501\u5b9a\u7ed9\u5173\u6389\nd.app_start(\"com.example.hello_world\", use_monkey=True) # start with package name\n\n# \u901a\u8fc7\u6307\u5b9amain activity\u7684\u65b9\u5f0f\u542f\u52a8\u5e94\u7528\uff0c\u7b49\u4ef7\u4e8e\u8c03\u7528am start -n com.example.hello_world/.MainActivity\nd.app_start(\"com.example.hello_world\", \".MainActivity\")\n```\n\n### Stop an app\n```python\n# equivalent to `am force-stop`, thus you could lose data\nd.app_stop(\"com.example.hello_world\") \n# equivalent to `pm clear`\nd.app_clear('com.example.hello_world')\n```\n\n### Stop all running apps\n```python\n# stop all\nd.app_stop_all()\n# stop all app except for com.examples.demo\nd.app_stop_all(excludes=['com.examples.demo'])\n```\n\n### Get app info\n```python\nd.app_info(\"com.examples.demo\")\n# expect output\n#{\n#    \"mainActivity\": \"com.github.uiautomator.MainActivity\",\n#    \"label\": \"ATX\",\n#    \"versionName\": \"1.1.7\",\n#    \"versionCode\": 1001007,\n#    \"size\":1760809\n#}\n\n# save app icon\nimg = d.app_icon(\"com.examples.demo\")\nimg.save(\"icon.png\")\n```\n\n### List all running apps\n```python\nd.app_list_running()\n# expect output\n# [\"com.xxxx.xxxx\", \"com.github.uiautomator\", \"xxxx\"]\n```\n\n### Wait until app running\n```python\npid = d.app_wait(\"com.example.android\") # \u7b49\u5f85\u5e94\u7528\u8fd0\u884c, return pid(int)\nif not pid:\n    print(\"com.example.android is not running\")\nelse:\n    print(\"com.example.android pid is %d\" % pid)\n\nd.app_wait(\"com.example.android\", front=True) # \u7b49\u5f85\u5e94\u7528\u524d\u53f0\u8fd0\u884c\nd.app_wait(\"com.example.android\", timeout=20.0) # \u6700\u957f\u7b49\u5f85\u65f6\u95f420s\uff08\u9ed8\u8ba4\uff09\n```\n\n> Added in version 1.2.0\n\n### Push and pull files\n* push a file to the device\n\n    ```python\n    # push to a folder\n    d.push(\"foo.txt\", \"/sdcard/\")\n    # push and rename\n    d.push(\"foo.txt\", \"/sdcard/bar.txt\")\n    # push fileobj\n    with open(\"foo.txt\", 'rb') as f:\n        d.push(f, \"/sdcard/\")\n    # push and change file access mode\n    d.push(\"foo.sh\", \"/data/local/tmp/\", mode=0o755)\n    ```\n\n* pull a file from the device\n\n    ```python\n    d.pull(\"/sdcard/tmp.txt\", \"tmp.txt\")\n\n    # FileNotFoundError will raise if the file is not found on the device\n    d.pull(\"/sdcard/some-file-not-exists.txt\", \"tmp.txt\")\n    ```\n\n### Other app operations\n\n```python\n# grant all the permissions\nd.app_auto_grant_permissions(\"io.appium.android.apis\")\n\n# open scheme\nd.open_url(\"appname://appnamehost\")\n# same as\n# adb shell am start -a android.intent.action.VIEW -d \"appname://appnamehost\"\n```\n\n## Basic API Usages\nThis part showcases how to perform common device operations:\n\n### Shell commands\n* Run a short-lived shell command with a timeout protection. (Default timeout 60s)\n\n    Note: timeout support require `atx-agent >=0.3.3`\n\n    `adb_shell` function is deprecated. Use `shell` instead.\n\n    Simple usage\n\n    ```python\n    output, exit_code = d.shell(\"pwd\", timeout=60) # timeout 60s (Default)\n    # output: \"/\\n\", exit_code: 0\n    # Similar to command: adb shell pwd\n\n    # Since `shell` function return type is `namedtuple(\"ShellResponse\", (\"output\", \"exit_code\"))`\n    # so we can do some tricks\n    output = d.shell(\"pwd\").output\n    exit_code = d.shell(\"pwd\").exit_code\n    ```\n\n    The first argument can be list. for example\n\n    ```python\n    output, exit_code = d.shell([\"ls\", \"-l\"])\n    # output: \"/....\", exit_code: 0\n    ```\n\n   This returns a string for stdout merged with stderr.\n   If the command is a blocking command, `shell` will also block until the command is completed or the timeout kicks in. No partial output will be received during the execution of the command. This API is not suitable for long-running commands. The shell command given runs in a similar environment of `adb shell`, which has a Linux permission level of `adb` or `shell` (higher than an app permission).\n\n* Run a long-running shell command (Removed)\n<!-- \n    add stream=True will return `requests.models.Response` object. More info see [requests stream](http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#id5)\n\n    ```python\n    r = d.shell(\"logcat\", stream=True)\n    # r: requests.models.Response\n    deadline = time.time() + 10 # run maxium 10s\n    try:\n        for line in r.iter_lines(): # r.iter_lines(chunk_size=512, decode_unicode=None, delimiter=None)\n            if time.time() > deadline:\n                break\n            print(\"Read:\", line.decode('utf-8'))\n    finally:\n        r.close() # this method must be called\n    ```\n\n    Command will be terminated when `r.close()` called. -->\n    \n### Session\nSession represent an app lifecycle. Can be used to start app, detect app crash.\n\n* Launch and close app\n\n    ```python\n    sess = d.session(\"com.netease.cloudmusic\") # start \u7f51\u6613\u4e91\u97f3\u4e50\n    sess.close() # \u505c\u6b62\u7f51\u6613\u4e91\u97f3\u4e50\n    sess.restart() # \u51b7\u542f\u52a8\u7f51\u6613\u4e91\u97f3\u4e50\n    ```\n\n* Use python `with` to launch and close app\n\n    ```python\n    with d.session(\"com.netease.cloudmusic\") as sess:\n        sess(text=\"Play\").click()\n    ```\n\n* Attach to the running app\n\n    ```python\n    # launch app if not running, skip launch if already running\n    sess = d.session(\"com.netease.cloudmusic\", attach=True)\n    ```\n\n* Detect app crash\n\n    ```python\n    # When app is still running\n    sess(text=\"Music\").click() # operation goes normal\n\n    # If app crash or quit\n    sess(text=\"Music\").click() # raise SessionBrokenError\n    # other function calls under session will raise SessionBrokenError too\n    ```\n\n    ```python\n    # check if session is ok.\n    # Warning: function name may change in the future\n    sess.running() # True or False\n    ```\n\n\n### Retrieve the device info\n\nGet basic information\n\n```python\nd.info\n```\n\nBelow is a possible output:\n\n```\n{'currentPackageName': 'com.android.systemui',\n 'displayHeight': 1560,\n 'displayRotation': 0,\n 'displaySizeDpX': 360,\n 'displaySizeDpY': 780,\n 'displayWidth': 720,\n 'naturalOrientation': True,\n 'productName': 'ELE-AL00',\n 'screenOn': True,\n 'sdkInt': 29}\n```\n\nGet window size\n\n```python\nprint(d.window_size())\n# device upright output example: (1080, 1920)\n# device horizontal output example: (1920, 1080)\n```\n\nGet current app info. For some android devices, the output could be empty (see *Output example 3*)\n\n```python\nprint(d.app_current())\n# Output example 1: {'activity': '.Client', 'package': 'com.netease.example', 'pid': 23710}\n# Output example 2: {'activity': '.Client', 'package': 'com.netease.example'}\n# Output example 3: {'activity': None, 'package': None}\n```\n\nWait activity\n\n```python\nd.wait_activity(\".ApiDemos\", timeout=10) # default timeout 10.0 seconds\n# Output: true of false\n```\n\nGet device serial number\n\n```python\nprint(d.serial)\n# output example: 74aAEDR428Z9\n```\n\nGet WLAN ip\n\n```python\nprint(d.wlan_ip)\n# output example: 10.0.0.1 or None\n```\n\n\n~~Get detailed device info~~ `d.device_info`\n\ndevice_info\n\n```python\nprint(d.device_info)\n```\n\nBelow is a possible output:\n\n```\n{'arch': 'arm64-v8a',\n 'brand': 'google',\n 'model': 'sdk_gphone64_arm64',\n 'sdk': 34,\n 'serial': 'EMULATOR34X1X19X0',\n 'version': 14}\n```\n\n### Clipboard\nGet of set clipboard content\n\n\u8bbe\u7f6e\u7c98\u8d34\u677f\u5185\u5bb9\u6216\u83b7\u53d6\u5185\u5bb9\n\n* clipboard/set_clipboard\n\n    ```python\n    d.clipboard = 'hello-world'\n    # or\n    d.set_clipboard('hello-world', 'label')\n\n    ```\n\nGet clipboard content\n\n>  get clipboard requires IME(com.github.uiautomator/.AdbKeyboard) call `d.set_input_ime()` before using it.\n\n    ```python\n    \n    # get clipboard content\n    print(d.clipboard)\n    ```\n\n### Key Events\n\n* Turn on/off screen\n\n    ```python\n    d.screen_on() # turn on the screen\n    d.screen_off() # turn off the screen\n    ```\n\n* Get current screen status\n\n    ```python\n    d.info.get('screenOn') # require Android >= 4.4\n    ```\n\n* Press hard/soft key\n\n    ```python\n    d.press(\"home\") # press the home key, with key name\n    d.press(\"back\") # press the back key, with key name\n    d.press(0x07, 0x02) # press keycode 0x07('0') with META ALT(0x02)\n    ```\n\n* These key names are currently supported:\n\n    - home\n    - back\n    - left\n    - right\n    - up\n    - down\n    - center\n    - menu\n    - search\n    - enter\n    - delete ( or del)\n    - recent (recent apps)\n    - volume_up\n    - volume_down\n    - volume_mute\n    - camera\n    - power\n\nYou can find all key code definitions at [Android KeyEvnet](https://developer.android.com/reference/android/view/KeyEvent.html)\n\n* Unlock screen\n\n    ```python\n    d.unlock()\n    # This is equivalent to\n    # 1. press(\"power\")\n    # 2. swipe from left-bottom to right-top\n    ```\n\n### Gesture interaction with the device\n* Click on the screen\n\n    ```python\n    d.click(x, y)\n    ```\n\n* Double click\n\n    ```python\n    d.double_click(x, y)\n    d.double_click(x, y, 0.1) # default duration between two click is 0.1s\n    ```\n\n* Long click on the screen\n\n    ```python\n    d.long_click(x, y)\n    d.long_click(x, y, 0.5) # long click 0.5s (default)\n    ```\n\n* Swipe\n\n    ```python\n    d.swipe(sx, sy, ex, ey)\n    d.swipe(sx, sy, ex, ey, 0.5) # swipe for 0.5s(default)\n    ```\n\n* SwipeExt \u6269\u5c55\u529f\u80fd\n\n    ```python\n    d.swipe_ext(\"right\") # \u624b\u6307\u53f3\u6ed1\uff0c4\u90091 \"left\", \"right\", \"up\", \"down\"\n    d.swipe_ext(\"right\", scale=0.9) # \u9ed8\u8ba40.9, \u6ed1\u52a8\u8ddd\u79bb\u4e3a\u5c4f\u5e55\u5bbd\u5ea6\u768490%\n    d.swipe_ext(\"right\", box=(0, 0, 100, 100)) # \u5728 (0,0) -> (100, 100) \u8fd9\u4e2a\u533a\u57df\u505a\u6ed1\u52a8\n\n\t# \u5b9e\u8df5\u53d1\u73b0\u4e0a\u6ed1\u6216\u4e0b\u6ed1\u7684\u65f6\u5019\uff0c\u4ece\u4e2d\u70b9\u5f00\u59cb\u6ed1\u52a8\u6210\u529f\u7387\u4f1a\u9ad8\u4e00\u4e9b\n\td.swipe_ext(\"up\", scale=0.8) # \u4ee3\u7801\u4f1avkk\n\n    # \u8fd8\u53ef\u4ee5\u4f7f\u7528Direction\u4f5c\u4e3a\u53c2\u6570\n    from uiautomator2 import Direction\n    \n    d.swipe_ext(Direction.FORWARD) # \u9875\u9762\u4e0b\u7ffb, \u7b49\u4ef7\u4e8e d.swipe_ext(\"up\"), \u53ea\u662f\u66f4\u597d\u7406\u89e3\n    d.swipe_ext(Direction.BACKWARD) # \u9875\u9762\u4e0a\u7ffb\n    d.swipe_ext(Direction.HORIZ_FORWARD) # \u9875\u9762\u6c34\u5e73\u53f3\u7ffb\n    d.swipe_ext(Direction.HORIZ_BACKWARD) # \u9875\u9762\u6c34\u5e73\u5de6\u7ffb\n    ```\n\n* Drag\n\n    ```python\n    d.drag(sx, sy, ex, ey)\n    d.drag(sx, sy, ex, ey, 0.5) # swipe for 0.5s(default)\n\n* Swipe points\n\n    ```python\n    # swipe from point(x0, y0) to point(x1, y1) then to point(x2, y2)\n    # time will speed 0.2s bwtween two points\n    d.swipe_points([(x0, y0), (x1, y1), (x2, y2)], 0.2))\n    ```\n\n    \u591a\u7528\u4e8e\u4e5d\u5bab\u683c\u89e3\u9501\uff0c\u63d0\u524d\u83b7\u53d6\u5230\u6bcf\u4e2a\u70b9\u7684\u76f8\u5bf9\u5750\u6807\uff08\u8fd9\u91cc\u652f\u6301\u767e\u5206\u6bd4\uff09\uff0c\n    \u66f4\u8be6\u7ec6\u7684\u4f7f\u7528\u53c2\u8003\u8fd9\u4e2a\u5e16\u5b50 [\u4f7f\u7528u2\u5b9e\u73b0\u4e5d\u5bab\u56fe\u6848\u89e3\u9501](https://testerhome.com/topics/11034)\n\n* Touch and drap (Beta)\n\n    \u8fd9\u4e2a\u63a5\u53e3\u5c5e\u4e8e\u6bd4\u8f83\u5e95\u5c42\u7684\u539f\u59cb\u63a5\u53e3\uff0c\u611f\u89c9\u5e76\u4e0d\u5b8c\u5584\uff0c\u4e0d\u8fc7\u51d1\u5408\u80fd\u7528\u3002\u6ce8\uff1a\u8fd9\u4e2a\u5730\u65b9\u5e76\u4e0d\u652f\u6301\u767e\u5206\u6bd4\n\n    ```python\n    d.touch.down(10, 10) # \u6a21\u62df\u6309\u4e0b\n    time.sleep(.01) # down \u548c move \u4e4b\u95f4\u7684\u5ef6\u8fdf\uff0c\u81ea\u5df1\u63a7\u5236\n    d.touch.move(15, 15) # \u6a21\u62df\u79fb\u52a8\n    d.touch.up(10, 10) # \u6a21\u62df\u62ac\u8d77\n    ```\n\nNote: click, swipe, drag operations support percentage position values. Example:\n\n`d.long_click(0.5, 0.5)` means long click center of screen\n\n### Screen-related\n* Retrieve/Set device orientation\n\n    The possible orientations:\n\n    -   `natural` or `n`\n    -   `left` or `l`\n    -   `right` or `r`\n    -   `upsidedown` or `u` (can not be set)\n\n    ```python\n    # retrieve orientation. the output could be \"natural\" or \"left\" or \"right\" or \"upsidedown\"\n    orientation = d.orientation\n\n    # WARNING: not pass testing in my TT-M1\n    # set orientation and freeze rotation.\n    # notes: setting \"upsidedown\" requires Android>=4.3.\n    d.set_orientation('l') # or \"left\"\n    d.set_orientation(\"l\") # or \"left\"\n    d.set_orientation(\"r\") # or \"right\"\n    d.set_orientation(\"n\") # or \"natural\"\n    ```\n\n* Freeze/Un-freeze rotation\n\n    ```python\n    # freeze rotation\n    d.freeze_rotation()\n    # un-freeze rotation\n    d.freeze_rotation(False)\n    ```\n\n* Take screenshot\n\n    ```python\n    # take screenshot and save to a file on the computer, require Android>=4.2.\n    d.screenshot(\"home.jpg\")\n    \n    # get PIL.Image formatted images. Naturally, you need pillow installed first\n    image = d.screenshot() # default format=\"pillow\"\n    image.save(\"home.jpg\") # or home.png. Currently, only png and jpg are supported\n\n    # get opencv formatted images. Naturally, you need numpy and cv2 installed first\n    import cv2\n    image = d.screenshot(format='opencv')\n    cv2.imwrite('home.jpg', image)\n\n    # get raw jpeg data\n    imagebin = d.screenshot(format='raw')\n    open(\"some.jpg\", \"wb\").write(imagebin)\n    ```\n\n* Dump UI hierarchy\n\n    ```python\n    # get the UI hierarchy dump content\n    xml = d.dump_hierarchy()\n\n    # compressed=True: include not import nodes\n    # pretty: format xml\n    # max_depth: limit xml depth, default 50\n    xml = d.dump_hierarchy(compressed=False, pretty=False, max_depth=50)\n    ```\n\n* Open notification or quick settings\n\n    ```python\n    d.open_notification()\n    d.open_quick_settings()\n    ```\n\n### Selector\n\nSelector is a handy mechanism to identify a specific UI object in the current window.\n\n```python\n# Select the object with text 'Clock' and its className is 'android.widget.TextView'\nd(text='Clock', className='android.widget.TextView')\n```\n\nSelector supports below parameters. Refer to [UiSelector Java doc](http://developer.android.com/tools/help/uiautomator/UiSelector.html) for detailed information.\n\n*  `text`, `textContains`, `textMatches`, `textStartsWith`\n*  `className`, `classNameMatches`\n*  `description`, `descriptionContains`, `descriptionMatches`, `descriptionStartsWith`\n*  `checkable`, `checked`, `clickable`, `longClickable`\n*  `scrollable`, `enabled`,`focusable`, `focused`, `selected`\n*  `packageName`, `packageNameMatches`\n*  `resourceId`, `resourceIdMatches`\n*  `index`, `instance`\n\n#### Children and siblings\n\n* children\n\n  ```python\n  # get the children or grandchildren\n  d(className=\"android.widget.ListView\").child(text=\"Bluetooth\")\n  ```\n\n* siblings\n\n  ```python\n  # get siblings\n  d(text=\"Google\").sibling(className=\"android.widget.ImageView\")\n  ```\n\n* children by text or description or instance\n\n  ```python\n  # get the child matching the condition className=\"android.widget.LinearLayout\"\n  # and also its children or grandchildren with text \"Bluetooth\"\n  d(className=\"android.widget.ListView\", resourceId=\"android:id/list\") \\\n   .child_by_text(\"Bluetooth\", className=\"android.widget.LinearLayout\")\n\n  # get children by allowing scroll search\n  d(className=\"android.widget.ListView\", resourceId=\"android:id/list\") \\\n   .child_by_text(\n      \"Bluetooth\",\n      allow_scroll_search=True,\n      className=\"android.widget.LinearLayout\"\n    )\n  ```\n\n  - `child_by_description` is to find children whose grandchildren have\n      the specified description, other parameters being similar to `child_by_text`.\n\n  - `child_by_instance` is to find children with has a child UI element anywhere\n      within its sub hierarchy that is at the instance specified. It is performed\n      on visible views **without scrolling**.\n\n  See below links for detailed information:\n\n  -   [UiScrollable](http://developer.android.com/tools/help/uiautomator/UiScrollable.html), `getChildByDescription`, `getChildByText`, `getChildByInstance`\n  -   [UiCollection](http://developer.android.com/tools/help/uiautomator/UiCollection.html), `getChildByDescription`, `getChildByText`, `getChildByInstance`\n\n  Above methods support chained invoking, e.g. for below hierarchy\n\n  ```xml\n  <node index=\"0\" text=\"\" resource-id=\"android:id/list\" class=\"android.widget.ListView\" ...>\n    <node index=\"0\" text=\"WIRELESS & NETWORKS\" resource-id=\"\" class=\"android.widget.TextView\" .../>\n    <node index=\"1\" text=\"\" resource-id=\"\" class=\"android.widget.LinearLayout\" ...>\n      <node index=\"1\" text=\"\" resource-id=\"\" class=\"android.widget.RelativeLayout\" ...>\n        <node index=\"0\" text=\"Wi\u2011Fi\" resource-id=\"android:id/title\" class=\"android.widget.TextView\" .../>\n      </node>\n      <node index=\"2\" text=\"ON\" resource-id=\"com.android.settings:id/switchWidget\" class=\"android.widget.Switch\" .../>\n    </node>\n    ...\n  </node>\n  ```\n  ![settings](https://raw.github.com/xiaocong/uiautomator/master/docs/img/settings.png)\n\n  To click the switch widget right to the TextView 'Wi\u2011Fi', we need to select the switch widgets first. However, according to the UI hierarchy, more than one switch widgets exist and have almost the same properties. Selecting by className will not work. Alternatively, the below selecting strategy would help:\n\n  ```python\n  d(className=\"android.widget.ListView\", resourceId=\"android:id/list\") \\\n    .child_by_text(\"Wi\u2011Fi\", className=\"android.widget.LinearLayout\") \\\n    .child(className=\"android.widget.Switch\") \\\n    .click()\n  ```\n\n* relative positioning\n\n  Also we can use the relative positioning methods to get the view: `left`, `right`, `top`, `bottom`.\n\n  -   `d(A).left(B)`, selects B on the left side of A.\n  -   `d(A).right(B)`, selects B on the right side of A.\n  -   `d(A).up(B)`, selects B above A.\n  -   `d(A).down(B)`, selects B under A.\n\n  So for above cases, we can alternatively select it with:\n\n  ```python\n  ## select \"switch\" on the right side of \"Wi\u2011Fi\"\n  d(text=\"Wi\u2011Fi\").right(className=\"android.widget.Switch\").click()\n  ```\n\n* Multiple instances\n\n  Sometimes the screen may contain multiple views with the same properties, e.g. text, then you will\n  have to use the \"instance\" property in the selector to pick one of qualifying instances, like below:\n\n  ```python\n  d(text=\"Add new\", instance=0)  # which means the first instance with text \"Add new\"\n  ```\n\n  In addition, uiautomator2 provides a list-like API (similar to jQuery):\n\n  ```python\n  # get the count of views with text \"Add new\" on current screen\n  d(text=\"Add new\").count\n\n  # same as count property\n  len(d(text=\"Add new\"))\n\n  # get the instance via index\n  d(text=\"Add new\")[0]\n  d(text=\"Add new\")[1]\n  ...\n\n  # iterator\n  for view in d(text=\"Add new\"):\n      view.info  # ...\n  ```\n\n  **Notes**: when using selectors in a code block that walk through the result list, you must ensure that the UI elements on the screen\n  keep unchanged. Otherwise, when Element-Not-Found error could occur when iterating through the list.\n\n#### Get the selected ui object status and its information\n* Check if the specific UI object exists\n\n    ```python\n    d(text=\"Settings\").exists # True if exists, else False\n    d.exists(text=\"Settings\") # alias of above property.\n\n    # advanced usage\n    d(text=\"Settings\").exists(timeout=3) # wait Settings appear in 3s, same as .wait(3)\n    ```\n\n* Retrieve the info of the specific UI object\n\n    ```python\n    d(text=\"Settings\").info\n    ```\n\n    Below is a possible output:\n\n    ```\n    { u'contentDescription': u'',\n    u'checked': False,\n    u'scrollable': False,\n    u'text': u'Settings',\n    u'packageName': u'com.android.launcher',\n    u'selected': False,\n    u'enabled': True,\n    u'bounds': {u'top': 385,\n                u'right': 360,\n                u'bottom': 585,\n                u'left': 200},\n    u'className': u'android.widget.TextView',\n    u'focused': False,\n    u'focusable': True,\n    u'clickable': True,\n    u'chileCount': 0,\n    u'longClickable': True,\n    u'visibleBounds': {u'top': 385,\n                        u'right': 360,\n                        u'bottom': 585,\n                        u'left': 200},\n    u'checkable': False\n    }\n    ```\n\n* Get/Set/Clear text of an editable field (e.g., EditText widgets)\n\n    ```python\n    d(text=\"Settings\").get_text()  # get widget text\n    d(text=\"Settings\").set_text(\"My text...\")  # set the text\n    d(text=\"Settings\").clear_text()  # clear the text\n    ```\n\n* Get Widget center point\n\n    ```python\n    x, y = d(text=\"Settings\").center()\n    # x, y = d(text=\"Settings\").center(offset=(0, 0)) # left-top x, y\n    ```\n    \n* Take screenshot of widget\n\n    ```python\n    im = d(text=\"Settings\").screenshot()\n    im.save(\"settings.jpg\")\n    ```\n\n#### Perform the click action on the selected UI object\n* Perform click on the specific   object\n\n    ```python\n    # click on the center of the specific ui object\n    d(text=\"Settings\").click()\n    \n    # wait element to appear for at most 10 seconds and then click\n    d(text=\"Settings\").click(timeout=10)\n    \n    # click with offset(x_offset, y_offset)\n    # click_x = x_offset * width + x_left_top\n    # click_y = y_offset * height + y_left_top\n    d(text=\"Settings\").click(offset=(0.5, 0.5)) # Default center\n    d(text=\"Settings\").click(offset=(0, 0)) # click left-top\n    d(text=\"Settings\").click(offset=(1, 1)) # click right-bottom\n\n    # click when exists in 10s, default timeout 0s\n    clicked = d(text='Skip').click_exists(timeout=10.0)\n    \n    # click until element gone, return bool\n    is_gone = d(text=\"Skip\").click_gone(maxretry=10, interval=1.0) # maxretry default 10, interval default 1.0\n    ```\n\n* Perform long click on the specific UI object\n\n    ```python\n    # long click on the center of the specific UI object\n    d(text=\"Settings\").long_click()\n    ```\n\n#### Gesture actions for the specific UI object\n* Drag the UI object towards another point or another UI object \n\n    ```python\n    # notes : drag can not be used for Android<4.3.\n    # drag the UI object to a screen point (x, y), in 0.5 second\n    d(text=\"Settings\").drag_to(x, y, duration=0.5)\n    # drag the UI object to (the center position of) another UI object, in 0.25 second\n    d(text=\"Settings\").drag_to(text=\"Clock\", duration=0.25)\n    ```\n\n* Swipe from the center of the UI object to its edge\n\n    Swipe supports 4 directions:\n\n    - left\n    - right\n    - top\n    - bottom\n\n    ```python\n    d(text=\"Settings\").swipe(\"right\")\n    d(text=\"Settings\").swipe(\"left\", steps=10)\n    d(text=\"Settings\").swipe(\"up\", steps=20) # 1 steps is about 5ms, so 20 steps is about 0.1s\n    d(text=\"Settings\").swipe(\"down\", steps=20)\n    ```\n\n* Two-point gesture from one point to another\n\n  ```python\n  d(text=\"Settings\").gesture((sx1, sy1), (sx2, sy2), (ex1, ey1), (ex2, ey2))\n  ```\n\n* Two-point gesture on the specific UI object\n\n  Supports two gestures:\n  - `In`, from edge to center\n  - `Out`, from center to edge\n\n  ```python\n  # notes : pinch can not be set until Android 4.3.\n  # from edge to center. here is \"In\" not \"in\"\n  d(text=\"Settings\").pinch_in(percent=100, steps=10)\n  # from center to edge\n  d(text=\"Settings\").pinch_out()\n  ```\n\n* Wait until the specific UI appears or disappears\n    \n    ```python\n    # wait until the ui object appears\n    d(text=\"Settings\").wait(timeout=3.0) # return bool\n    # wait until the ui object gone\n    d(text=\"Settings\").wait_gone(timeout=1.0)\n    ```\n\n    The default timeout is 20s. see **global settings** for more details\n\n* Perform fling on the specific ui object(scrollable)\n\n  Possible properties:\n  - `horiz` or `vert`\n  - `forward` or `backward` or `toBeginning` or `toEnd`\n\n  ```python\n  # fling forward(default) vertically(default) \n  d(scrollable=True).fling()\n  # fling forward horizontally\n  d(scrollable=True).fling.horiz.forward()\n  # fling backward vertically\n  d(scrollable=True).fling.vert.backward()\n  # fling to beginning horizontally\n  d(scrollable=True).fling.horiz.toBeginning(max_swipes=1000)\n  # fling to end vertically\n  d(scrollable=True).fling.toEnd()\n  ```\n\n* Perform scroll on the specific ui object(scrollable)\n\n  Possible properties:\n  - `horiz` or `vert`\n  - `forward` or `backward` or `toBeginning` or `toEnd`, or `to`\n\n  ```python\n  # scroll forward(default) vertically(default)\n  d(scrollable=True).scroll(steps=10)\n  # scroll forward horizontally\n  d(scrollable=True).scroll.horiz.forward(steps=100)\n  # scroll backward vertically\n  d(scrollable=True).scroll.vert.backward()\n  # scroll to beginning horizontally\n  d(scrollable=True).scroll.horiz.toBeginning(steps=100, max_swipes=1000)\n  # scroll to end vertically\n  d(scrollable=True).scroll.toEnd()\n  # scroll forward vertically until specific ui object appears\n  d(scrollable=True).scroll.to(text=\"Security\")\n  ```\n\n### WatchContext\n\u76ee\u524d\u7684\u8fd9\u4e2awatch_context\u662f\u7528threading\u542f\u52a8\u7684\uff0c\u6bcf2s\u68c0\u67e5\u4e00\u6b21\n\u76ee\u524d\u8fd8\u53ea\u6709click\u8fd9\u4e00\u79cd\u89e6\u53d1\u64cd\u4f5c\n\n```python\nwith d.watch_context() as ctx:\n    # \u5f53\u540c\u65f6\u51fa\u73b0 \uff08\u7acb\u5373\u4e0b\u8f7d \u6216 \u7acb\u5373\u66f4\u65b0\uff09\u548c \u53d6\u6d88 \u6309\u94ae\u7684\u65f6\u5019\uff0c\u70b9\u51fb\u53d6\u6d88\n    ctx.when(\"^\u7acb\u5373(\u4e0b\u8f7d|\u66f4\u65b0)\").when(\"\u53d6\u6d88\").click() \n    ctx.when(\"\u540c\u610f\").click()\n    ctx.when(\"\u786e\u5b9a\").click()\n    # \u4e0a\u9762\u4e09\u884c\u4ee3\u7801\u662f\u7acb\u5373\u6267\u884c\u5b8c\u7684\uff0c\u4e0d\u4f1a\u6709\u4ec0\u4e48\u7b49\u5f85\n    \n    ctx.wait_stable() # \u5f00\u542f\u5f39\u7a97\u76d1\u63a7\uff0c\u5e76\u7b49\u5f85\u754c\u9762\u7a33\u5b9a\uff08\u4e24\u4e2a\u5f39\u7a97\u68c0\u67e5\u5468\u671f\u5185\u6ca1\u6709\u5f39\u7a97\u4ee3\u8868\u7a33\u5b9a\uff09\n\n    # \u4f7f\u7528call\u51fd\u6570\u6765\u89e6\u53d1\u51fd\u6570\u56de\u8c03\n    # call \u652f\u6301\u4e24\u4e2a\u53c2\u6570\uff0cd\u548cel\uff0c\u4e0d\u533a\u5206\u53c2\u6570\u4f4d\u7f6e\uff0c\u53ef\u4ee5\u4e0d\u4f20\u53c2\uff0c\u5982\u679c\u4f20\u53c2\u53d8\u91cf\u540d\u4e0d\u80fd\u5199\u9519\n    # eg: \u5f53\u6709\u5143\u7d20\u5339\u914d\u4ef2\u590f\u4e4b\u591c\uff0c\u70b9\u51fb\u8fd4\u56de\u6309\u94ae\n    ctx.when(\"\u4ef2\u590f\u4e4b\u591c\").call(lambda d: d.press(\"back\"))\n    ctx.when(\"\u786e\u5b9a\").call(lambda el: el.click())\n\n    # \u5176\u4ed6\u64cd\u4f5c\n\n# \u4e3a\u4e86\u65b9\u4fbf\u4e5f\u53ef\u4ee5\u4f7f\u7528\u4ee3\u7801\u4e2d\u9ed8\u8ba4\u7684\u5f39\u7a97\u76d1\u63a7\u903b\u8f91\n# \u4e0b\u9762\u662f\u76ee\u524d\u5185\u7f6e\u7684\u9ed8\u8ba4\u903b\u8f91\uff0c\u53ef\u4ee5\u52a0\u7fa4at\u7fa4\u4e3b\uff0c\u589e\u52a0\u65b0\u7684\u903b\u8f91\uff0c\u6216\u8005\u76f4\u63a5\u63d0pr\n    # when(\"\u7ee7\u7eed\u4f7f\u7528\").click()\n    # when(\"\u79fb\u5165\u7ba1\u63a7\").when(\"\u53d6\u6d88\").click()\n    # when(\"^\u7acb\u5373(\u4e0b\u8f7d|\u66f4\u65b0)\").when(\"\u53d6\u6d88\").click()\n    # when(\"\u540c\u610f\").click()\n    # when(\"^(\u597d\u7684|\u786e\u5b9a)\").click()\nwith d.watch_context(builtin=True) as ctx:\n    # \u5728\u5df2\u6709\u7684\u57fa\u7840\u4e0a\u589e\u52a0\n    ctx.when(\"@tb:id/jview_view\").when('//*[@content-desc=\"\u56fe\u7247\"]').click()\n\n    # \u5176\u4ed6\u811a\u672c\u903b\u8f91\n```\n\n\u53e6\u5916\u4e00\u79cd\u5199\u6cd5\n\n```python\nctx = d.watch_context()\nctx.when(\"\u8bbe\u7f6e\").click()\nctx.wait_stable() # \u7b49\u5f85\u754c\u9762\u4e0d\u5728\u6709\u5f39\u7a97\u4e86\n\nctx.close()\n```\n\n### Watcher\n**\u66f4\u63a8\u8350\u7528WatchContext** \u5199\u6cd5\u66f4\u7b80\u6d01\u4e00\u4e9b\n\n~~You can register [watchers](http://developer.android.com/tools/help/uiautomator/UiWatcher.html) to perform some actions when a selector does not find a match.~~\n\n2.0.0\u4e4b\u524d\u4f7f\u7528\u7684\u662f uiautomator-jar\u5e93\u4e2d\u63d0\u4f9b\u7684[Watcher]((http://developer.android.com/tools/help/uiautomator/UiWatcher.html)\u65b9\u6cd5\uff0c\u4f46\u5728\u5b9e\u8df5\u4e2d\u53d1\u73b0\u4e00\u65e6uiautomator\u8fde\u63a5\u5931\u8d25\u91cd\u542f\u4e86\uff0c\u6240\u6709\u7684watcher\u914d\u7f6e\u90fd\u662f\u4e22\u5931\uff0c\u8fd9\u80af\u5b9a\u662f\u65e0\u6cd5\u63a5\u53d7\u7684\u3002\n\n\u6240\u4ee5\u76ee\u524d\u91c7\u7528\u4e86\u540e\u53f0\u8fd0\u884c\u4e86\u4e00\u4e2a\u7ebf\u7a0b\u7684\u65b9\u6cd5(\u4f9d\u8d56threading\u5e93\uff09\uff0c\u7136\u540e\u6bcf\u9694\u4e00\u6bb5\u65f6\u95f4dump\u4e00\u6b21hierarchy\uff0c\u5339\u914d\u5230\u5143\u7d20\u4e4b\u540e\u6267\u884c\u76f8\u5e94\u7684\u64cd\u4f5c\u3002\n\n\u7528\u6cd5\u4e3e\u4f8b\n\n\u6ce8\u518c\u76d1\u63a7\n\n```python\n# \u5e38\u7528\u5199\u6cd5\uff0c\u6ce8\u518c\u533f\u540d\u76d1\u63a7\nd.watcher.when(\"\u5b89\u88c5\").click()\n\n# \u6ce8\u518c\u540d\u4e3aANR\u7684\u76d1\u63a7\uff0c\u5f53\u51fa\u73b0ANR\u548cForce Close\u65f6\uff0c\u70b9\u51fbForce Close\nd.watcher(\"ANR\").when(xpath=\"ANR\").when(\"Force Close\").click()\n\n# \u5176\u4ed6\u56de\u8c03\u4f8b\u5b50\nd.watcher.when(\"\u62a2\u7ea2\u5305\").press(\"back\")\nd.watcher.when(\"//*[@text = 'Out of memory']\").call(lambda d: d.shell('am force-stop com.im.qq'))\n\n# \u56de\u8c03\u8bf4\u660e\ndef click_callback(d: u2.Device):\n    d.xpath(\"\u786e\u5b9a\").click() # \u5728\u56de\u8c03\u4e2d\u8c03\u7528\u4e0d\u4f1a\u518d\u6b21\u89e6\u53d1watcher\n\nd.xpath(\"\u7ee7\u7eed\").click() # \u4f7f\u7528d.xpath\u68c0\u67e5\u5143\u7d20\u7684\u65f6\u5019\uff0c\u4f1a\u89e6\u53d1watcher\uff08\u76ee\u524d\u6700\u591a\u89e6\u53d15\u6b21\uff09\n\n# \u5f00\u59cb\u540e\u53f0\u76d1\u63a7\nd.watcher.start()\n```\n\n\u76d1\u63a7\u64cd\u4f5c\n\n```python\n# \u79fb\u9664ANR\u7684\u76d1\u63a7\nd.watcher.remove(\"ANR\")\n\n# \u79fb\u9664\u6240\u6709\u7684\u76d1\u63a7\nd.watcher.remove()\n\n# \u5f00\u59cb\u540e\u53f0\u76d1\u63a7\nd.watcher.start()\nd.watcher.start(2.0) # \u9ed8\u8ba4\u76d1\u63a7\u95f4\u96942.0s\n\n# \u5f3a\u5236\u8fd0\u884c\u6240\u6709\u76d1\u63a7\nd.watcher.run()\n\n# \u505c\u6b62\u76d1\u63a7\nd.watcher.stop()\n\n# \u505c\u6b62\u5e76\u79fb\u9664\u6240\u6709\u7684\u76d1\u63a7\uff0c\u5e38\u7528\u4e8e\u521d\u59cb\u5316\nd.watcher.reset()\n```\n\n\u53e6\u5916\u6587\u6863\u8fd8\u662f\u6709\u5f88\u591a\u6ca1\u6709\u5199\uff0c\u63a8\u8350\u76f4\u63a5\u53bb\u770b\u6e90\u7801[watcher.py](uiautomator2/watcher.py)\n\n### Global settings\n\n```python\nu2.HTTP_TIMEOUT = 60 # \u9ed8\u8ba4\u503c60s, http\u9ed8\u8ba4\u8bf7\u6c42\u8d85\u65f6\u65f6\u95f4\n```\n\n\u5176\u4ed6\u7684\u914d\u7f6e\uff0c\u76ee\u524d\u5df2\u5927\u90e8\u5206\u96c6\u4e2d\u5230 `d.settings` \u4e2d\uff0c\u6839\u636e\u540e\u671f\u7684\u9700\u6c42\u914d\u7f6e\u53ef\u80fd\u4f1a\u6709\u589e\u51cf\u3002\n\n```python\nprint(d.settings)\n{'operation_delay': (0, 0),\n 'operation_delay_methods': ['click', 'swipe'],\n 'wait_timeout': 20.0}\n\n# \u914d\u7f6e\u70b9\u51fb\u524d\u5ef6\u65f60.5s\uff0c\u70b9\u51fb\u540e\u5ef6\u65f61s\nd.settings['operation_delay'] = (.5, 1)\n\n# \u4fee\u6539\u5ef6\u8fdf\u751f\u6548\u7684\u65b9\u6cd5\n# \u5176\u4e2d double_click, long_click \u90fd\u5bf9\u5e94click\nd.settings['operation_delay_methods'] = ['click', 'swipe', 'drag', 'press']\nd.settings['wait_timeout'] = 20.0 # \u9ed8\u8ba4\u63a7\u4ef6\u7b49\u5f85\u65f6\u95f4\uff08\u539f\u751f\u64cd\u4f5c\uff0cxpath\u63d2\u4ef6\u7684\u7b49\u5f85\u65f6\u95f4\uff09\n\nd.settings['max_depth'] = 50 # \u9ed8\u8ba450\uff0c\u9650\u5236dump_hierarchy\u8fd4\u56de\u7684\u5143\u7d20\u5c42\u7ea7\n```\n\n\u5bf9\u4e8e\u968f\u7740\u7248\u672c\u5347\u7ea7\uff0c\u8bbe\u7f6e\u8fc7\u671f\u7684\u914d\u7f6e\u65f6\uff0c\u4f1a\u63d0\u793aDeprecated\uff0c\u4f46\u662f\u4e0d\u4f1a\u629b\u5f02\u5e38\u3002\n\n```bash\n>>> d.settings['click_before_delay'] = 1  \n[W 200514 14:55:59 settings:72] d.settings[click_before_delay] deprecated: Use operation_delay instead\n```\n\n**uiautomator\u6062\u590d\u65b9\u5f0f\u8bbe\u7f6e**\n\n\u7ec6\u5fc3\u7684\u4f60\u53ef\u80fd\u53d1\u73b0\uff0c\u5b9e\u9645\u4e0a\u624b\u673a\u5b89\u88c5\u4e86\u4e24\u4e2aAPK\uff0c\u4e00\u4e2a\u5728\u524d\u53f0\u53ef\u89c1\uff08\u5c0f\u9ec4\u8f66\uff09\u3002\u4e00\u4e2a\u5305\u540d\u4e3a`com.github.uiautomator.test`\u5728\u540e\u53f0\u4e0d\u53ef\u89c1\u3002\u8fd9\u4e24\u4e2aapk\u4f7f\u7528\u540c\u4e00\u4e2a\u8bc1\u4e66\u7b7e\u540d\u7684\u3002\n\u4e0d\u53ef\u89c1\u7684\u5e94\u7528\u5b9e\u9645\u4e0a\u662f\u4e00\u4e2a\u6d4b\u8bd5\u5305\uff0c\u5305\u542b\u6709\u6240\u6709\u7684\u6d4b\u8bd5\u4ee3\u7801\uff0c\u6838\u5fc3\u7684\u6d4b\u8bd5\u670d\u52a1\u4e5f\u662f\u901a\u8fc7\u5176\u542f\u52a8\u7684\u3002\n\u4f46\u662f\u8fd0\u884c\u7684\u65f6\u5019\uff0c\u7cfb\u7edf\u5374\u9700\u8981\u90a3\u4e2a\u5c0f\u9ec4\u8f66\u4e00\u76f4\u5728\u8fd0\u884c\uff08\u5728\u540e\u53f0\u8fd0\u884c\u4e5f\u53ef\u4ee5\uff09\u3002\u4e00\u65e6\u5c0f\u9ec4\u8f66\u5e94\u7528\u88ab\u6740\uff0c\u540e\u53f0\u8fd0\u884c\u7684\u6d4b\u8bd5\u670d\u52a1\u4e5f\u5f88\u5feb\u7684\u4f1a\u88ab\u6740\u6389\u3002\u5c31\u7b97\u4ec0\u4e48\u4e5f\u4e0d\u505a\uff0c\u5e94\u7528\u5e94\u7528\u5728\u540e\u53f0\uff0c\u4e5f\u4f1a\u5f88\u5feb\u88ab\u7cfb\u7edf\u56de\u6536\u6389\u3002\uff08\u8fd9\u91cc\u5e0c\u671b\u9ad8\u624b\u6307\u70b9\u4e00\u4e0b\uff0c\u5982\u4f55\u624d\u80fd\u4e0d\u4f9d\u8d56\u5c0f\u9ec4\u8f66\u5e94\u7528\uff0c\u611f\u89c9\u7406\u8bba\u4e0a\u662f\u53ef\u4ee5\u7684\uff0c\u4f46\u662f\u76ee\u524d\u6211\u8fd8\u4e0d\u4f1a\uff09\u3002\n\n~~\u8ba9\u5c0f\u9ec4\u8f66\u5728\u540e\u53f0\u8fd0\u884c\u6709\u4e24\u79cd\u65b9\u5f0f\uff0c\u4e00\u79cd\u542f\u52a8\u5e94\u7528\u540e\uff0c\u653e\u5230\u540e\u53f0\uff08\u9ed8\u8ba4\uff09\u3002\u53e6\u5916\u901a\u8fc7`am startservice`\u542f\u52a8\u4e00\u4e2a\u540e\u53f0\u670d\u52a1\u4e5f\u884c\u3002~~\n\n~~\u901a\u8fc7 `d.settings[\"uiautomator_runtest_app_background\"] = True` \u53ef\u4ee5\u8c03\u6574\u8be5\u884c\u4e3a\u3002True\u4ee3\u8868\u542f\u52a8\u5e94\u7528\uff0cFalse\u4ee3\u8868\u542f\u52a8\u670d\u52a1\u3002~~\n\nUiAutomator\u4e2d\u7684\u8d85\u65f6\u8bbe\u7f6e(\u9690\u85cf\u65b9\u6cd5)\n\n```python\n>> d.jsonrpc.getConfigurator() \n{'actionAcknowledgmentTimeout': 500,\n 'keyInjectionDelay': 0,\n 'scrollAcknowledgmentTimeout': 200,\n 'waitForIdleTimeout': 0,\n 'waitForSelectorTimeout': 0}\n\n>> d.jsonrpc.setConfigurator({\"waitForIdleTimeout\": 100})\n{'actionAcknowledgmentTimeout': 500,\n 'keyInjectionDelay': 0,\n 'scrollAcknowledgmentTimeout': 200,\n 'waitForIdleTimeout': 100,\n 'waitForSelectorTimeout': 0}\n```\n\n\u4e3a\u4e86\u9632\u6b62\u5ba2\u6237\u7aef\u7a0b\u5e8f\u54cd\u5e94\u8d85\u65f6\uff0c`waitForIdleTimeout`\u548c`waitForSelectorTimeout`\u76ee\u524d\u5df2\u6539\u4e3a`0`\n\nRefs: [Google uiautomator Configurator](https://developer.android.com/reference/android/support/test/uiautomator/Configurator)\n\n### Input method\n\u8fd9\u79cd\u65b9\u6cd5\u901a\u5e38\u7528\u4e8e\u4e0d\u77e5\u9053\u63a7\u4ef6\u7684\u60c5\u51b5\u4e0b\u7684\u8f93\u5165\u3002\n\n```python\n# \u76ee\u524d\u91c7\u7528\u4ece\u526a\u8d34\u677f\u7c98\u8d34\u7684\u65b9\u5f0f\u8f93\u5165\nd.send_keys(\"\u4f60\u597d123abcEFG\")\nd.send_keys(\"\u4f60\u597d123abcEFG\", clear=True)\n\nd.clear_text() # \u6e05\u9664\u8f93\u5165\u6846\u6240\u6709\u5185\u5bb9\n\nd.send_action() # \u6839\u636e\u8f93\u5165\u6846\u7684\u9700\u6c42\uff0c\u81ea\u52a8\u6267\u884c\u56de\u8f66\u3001\u641c\u7d22\u7b49\u6307\u4ee4, Added in version 3.1\n# \u4e5f\u53ef\u4ee5\u6307\u5b9a\u53d1\u9001\u7684\u8f93\u5165\u6cd5action, eg: d.send_action(\"search\") \u652f\u6301 go, search, send, next, done, previous\n```\n\n\n\n```python\nprint(d.current_ime()) # \u83b7\u53d6\u5f53\u524d\u8f93\u5165\u6cd5ID\n\n```\n\n> \u66f4\u591a\u53c2\u8003: [IME_ACTION_CODE](https://developer.android.com/reference/android/view/inputmethod/EditorInfo)\n\n### Toast\n```python\nprint(d.last_toast) # get last toast, if not toast return None\nd.clear_toast()\n```\n\n> Fixed in version 3.2.0\n\n### XPath\nJava uiautoamtor\u4e2d\u9ed8\u8ba4\u662f\u4e0d\u652f\u6301xpath\u7684\uff0c\u6240\u4ee5\u8fd9\u91cc\u5c5e\u4e8e\u6269\u5c55\u7684\u4e00\u4e2a\u529f\u80fd\u3002\u901f\u5ea6\u4e0d\u662f\u8fd9\u4e48\u7684\u5feb\u3002\n\nFor example: \u5176\u4e2d\u4e00\u4e2a\u8282\u70b9\u7684\u5185\u5bb9\n\n```xml\n<android.widget.TextView\n  index=\"2\"\n  text=\"05:19\"\n  resource-id=\"com.netease.cloudmusic:id/qf\"\n  package=\"com.netease.cloudmusic\"\n  content-desc=\"\"\n  checkable=\"false\" checked=\"false\" clickable=\"false\" enabled=\"true\" focusable=\"false\" focused=\"false\"\n  scrollable=\"false\" long-clickable=\"false\" password=\"false\" selected=\"false\" visible-to-user=\"true\"\n  bounds=\"[957,1602][1020,1636]\" />\n```\n\nxpath\u5b9a\u4f4d\u548c\u4f7f\u7528\u65b9\u6cd5\n\n\u6709\u4e9b\u5c5e\u6027\u7684\u540d\u5b57\u6709\u4fee\u6539\u9700\u8981\u6ce8\u610f\n\n```\ndescription -> content-desc\nresourceId -> resource-id\n```\n\n\u5e38\u89c1\u7528\u6cd5\n\n```python\n# wait exists 10s\nd.xpath(\"//android.widget.TextView\").wait(10.0)\n# find and click\nd.xpath(\"//*[@content-desc='\u5206\u4eab']\").click()\n# check exists\nif d.xpath(\"//android.widget.TextView[contains(@text, 'Se')]\").exists:\n    print(\"exists\")\n# get all text-view text, attrib and center point\nfor elem in d.xpath(\"//android.widget.TextView\").all():\n    print(\"Text:\", elem.text)\n    # Dictionary eg: \n    # {'index': '1', 'text': '999+', 'resource-id': 'com.netease.cloudmusic:id/qb', 'package': 'com.netease.cloudmusic', 'content-desc': '', 'checkable': 'false', 'checked': 'false', 'clickable': 'false', 'enabled': 'true', 'focusable': 'false', 'focused': 'false','scrollable': 'false', 'long-clickable': 'false', 'password': 'false', 'selected': 'false', 'visible-to-user': 'true', 'bounds': '[661,1444][718,1478]'}\n    print(\"Attrib:\", elem.attrib)\n    # Coordinate eg: (100, 200)\n    print(\"Position:\", elem.center())\n```\n\n\u70b9\u51fb\u67e5\u770b[\u5176\u4ed6XPath\u5e38\u89c1\u7528\u6cd5](XPATH.md)\n\n### Screenrecord (Deprecated)\n\u89c6\u9891\u5f55\u5236(\u5e9f\u5f03)\uff0c\u4f7f\u7528[scrcpy](https://github.com/Genymobile/scrcpy)\u6765\u4ee3\u66ff\u5427\n\n\u8fd9\u91cc\u6ca1\u6709\u4f7f\u7528\u624b\u673a\u4e2d\u81ea\u5e26\u7684screenrecord\u547d\u4ee4\uff0c\u662f\u901a\u8fc7\u83b7\u53d6\u624b\u673a\u56fe\u7247\u5408\u6210\u89c6\u9891\u7684\u65b9\u6cd5\uff0c\u6240\u4ee5\u9700\u8981\u5b89\u88c5\u4e00\u4e9b\u5176\u4ed6\u7684\u4f9d\u8d56\uff0c\u5982imageio, imageio-ffmpeg, numpy\u7b49\n\u56e0\u4e3a\u6709\u4e9b\u4f9d\u8d56\u6bd4\u8f83\u5927\uff0c\u63a8\u8350\u4f7f\u7528\u955c\u50cf\u5b89\u88c5\u3002\u76f4\u63a5\u8fd0\u884c\u4e0b\u9762\u7684\u547d\u4ee4\u5373\u53ef\u3002\n\n```bash\npip3 install -U \"uiautomator2[image]\" -i https://pypi.doubanio.com/simple\n```\n\n\u4f7f\u7528\u65b9\u6cd5\n\n```\nd.screenrecord('output.mp4')\n\ntime.sleep(10)\n# or do something else\n\nd.screenrecord.stop() # \u505c\u6b62\u5f55\u5236\u540e\uff0coutput.mp4\u6587\u4ef6\u624d\u80fd\u6253\u5f00\n```\n\n\u5f55\u5236\u7684\u65f6\u5019\u4e5f\u53ef\u4ee5\u6307\u5b9afps\uff08\u5f53\u524d\u662f20\uff09\uff0c\u8fd9\u4e2a\u503c\u662f\u7387\u4f4e\u4e8eminicap\u8f93\u51fa\u56fe\u7247\u7684\u901f\u5ea6\uff0c\u611f\u89c9\u5df2\u7ecf\u5f88\u597d\u4e86\uff0c\u4e0d\u5efa\u8bae\u4f60\u4fee\u6539\u3002\n\n# Enable uiautomator2 logger\n\n```python\nfrom uiautomator2 import enable_pretty_logging\nenable_pretty_logging()\n```\n\nOr\n\n```\nlogger = logging.getLogger(\"uiautomator2\")\n# setup logger\n```\n\n## Stop UiAutomator\nPython\u7a0b\u5e8f\u9000\u51fa\u4e86\uff0cUiAutomation\u5c31\u9000\u51fa\u4e86\u3002\n\u4e0d\u8fc7\u4e5f\u53ef\u4ee5\u901a\u8fc7\u63a5\u53e3\u7684\u65b9\u6cd5\u505c\u6b62\u670d\u52a1\n\n```python\nd.stop_uiautomator()\n```\n\n## Google UiAutomator 2.0\u548c1.x\u7684\u533a\u522b\nhttps://www.cnblogs.com/insist8089/p/6898181.html\n\n- \u65b0\u589e\u63a5\u53e3\uff1aUiObject2\u3001Until\u3001By\u3001BySelector\n- \u5f15\u5165\u65b9\u5f0f\uff1a2.0\u4e2d\uff0ccom.android.uiautomator.core.* \u5f15\u5165\u65b9\u5f0f\u88ab\u5e9f\u5f03\u3002\u6539\u4e3aandroid.support.test.uiautomator\n- \u6784\u5efa\u7cfb\u7edf\uff1aMaven \u548c/\u6216 Ant\uff081.x\uff09\uff1bGradle\uff082.0\uff09\n- \u4ea7\u751f\u7684\u6d4b\u8bd5\u5305\u7684\u5f62\u5f0f\uff1a\u4ecezip /jar\uff081.x\uff09 \u5230 apk\uff082.0\uff09\n- \u5728\u672c\u5730\u73af\u5883\u4ee5adb\u547d\u4ee4\u8fd0\u884cUIAutomator\u6d4b\u8bd5\uff0c\u542f\u52a8\u65b9\u5f0f\u7684\u5dee\u522b\uff1a   \n  adb shell uiautomator runtest UiTest.jar -c package.name.ClassName\uff081.x\uff09\n  adb shell am instrument -e class com.example.app.MyTest \n  com.example.app.test/android.support.test.runner.AndroidJUnitRunner\uff082.0\uff09\n- \u80fd\u5426\u4f7f\u7528Android\u670d\u52a1\u53ca\u63a5\u53e3\uff1f 1.x~\u4e0d\u80fd\uff1b2.0~\u80fd\u3002\n- og\u8f93\u51fa\uff1f \u4f7f\u7528System.out.print\u8f93\u51fa\u6d41\u56de\u663e\u81f3\u6267\u884c\u7aef\uff081.x\uff09\uff1b \u8f93\u51fa\u81f3Logcat\uff082.0\uff09\n- \u6267\u884c\uff1f\u6d4b\u8bd5\u7528\u4f8b\u65e0\u9700\u7ee7\u627f\u4e8e\u4efb\u4f55\u7236\u7c7b\uff0c\u65b9\u6cd5\u540d\u4e0d\u9650\uff0c\u4f7f\u7528\u6ce8\u89e3 Annotation\u8fdb\u884c\uff082.0\uff09;  \u9700\u8981\u7ee7\u627fUiAutomatorTestCase\uff0c\u6d4b\u8bd5\u65b9\u6cd5\u9700\u8981\u4ee5test\u5f00\u5934(1.x) \n\n\n## \u4f9d\u8d56\u9879\u76ee\n- uiautomator jsonrpc server<https://github.com/openatx/android-uiautomator-server/>\n- ~~uiautomator\u5b88\u62a4\u7a0b\u5e8f <https://github.com/openatx/atx-agent>~~\n\n# Contributors\n- codeskyblue ([@codeskyblue][])\n- Xiaocong He ([@xiaocong][])\n- Yuanyuan Zou ([@yuanyuan][])\n- Qian Jin ([@QianJin2013][])\n- Xu Jingjie ([@xiscoxu][])\n- Xia Mingyuan ([@mingyuan-xia][])\n- Artem Iglikov, Google Inc. ([@artikz][])\n\n[@codeskyblue]: https://github.com/codeskyblue\n[@xiaocong]: https://github.com/xiaocong\n[@yuanyuan]: https://github.com/yuanyuanzou\n[@QianJin2013]: https://github.com/QianJin2013\n[@xiscoxu]: https://github.com/xiscoxu\n[@mingyuan-xia]: https://github.com/mingyuan-xia\n[@artikz]: https://github.com/artikz\n\nOther [contributors](../../graphs/contributors)\n\n## \u5176\u4ed6\u4f18\u79c0\u7684\u9879\u76ee\n- https://github.com/atinfo/awesome-test-automation \u6240\u6709\u4f18\u79c0\u6d4b\u8bd5\u6846\u67b6\u7684\u96c6\u5408\uff0c\u5305\u7f57\u4e07\u8c61\n- [google/mobly](https://github.com/google/mobly) \u8c37\u6b4c\u5185\u90e8\u7684\u6d4b\u8bd5\u6846\u67b6\uff0c\u867d\u7136\u6211\u4e0d\u592a\u61c2\uff0c\u4f46\u662f\u611f\u89c9\u5f88\u597d\u7528\n- https://github.com/zhangzhao4444/Maxim \u57fa\u4e8eUiautomator\u7684monkey\n- http://www.sikulix.com/ \u57fa\u4e8e\u56fe\u50cf\u8bc6\u522b\u7684\u81ea\u52a8\u5316\u6d4b\u8bd5\u6846\u67b6\uff0c\u975e\u5e38\u7684\u8001\u724c\n- http://airtest.netease.com/ \u672c\u9879\u76ee\u7684\u524d\u8eab\uff0c\u540e\u6765\u88ab\u7f51\u6613\u5e7f\u5dde\u56e2\u961f\u63a5\u624b\u5e76\u7ee7\u7eed\u4f18\u5316\u3002\u5b9e\u73b0\u6709\u4e00\u4e2a\u4e0d\u9519\u7684IDE\n\n\u6392\u540d\u6709\u5148\u540e\uff0c\u6b22\u8fce\u8865\u5145\n\n# LICENSE\n[MIT](LICENSE)\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "uiautomator for android device",
    "version": "3.2.8",
    "project_urls": {
        "Homepage": "https://github.com/openatx/uiautomator2"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7fedd87de86bded5b7ca5ce21e2ba5328be04a60b7ce7f591c0bb6912b0a03bf",
                "md5": "ce835bdf2c339861740d91f4f6cc2766",
                "sha256": "b3287eff98581b47f1c1a7fcefd08f15d55ff55ee44e765caa5768a94672ff29"
            },
            "downloads": -1,
            "filename": "uiautomator2-3.2.8-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ce835bdf2c339861740d91f4f6cc2766",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 5195726,
            "upload_time": "2024-12-05T14:27:59",
            "upload_time_iso_8601": "2024-12-05T14:27:59.307260Z",
            "url": "https://files.pythonhosted.org/packages/7f/ed/d87de86bded5b7ca5ce21e2ba5328be04a60b7ce7f591c0bb6912b0a03bf/uiautomator2-3.2.8-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b892746aba119f556334719e0d1d9eef71c9646729585f0f9ee88567364041e9",
                "md5": "dd70c61948926b9b938cd1bc2b0ca43c",
                "sha256": "9a9ff08fc4b100471baef6ba93b464c1c3f35f1ee95bcd82bfcb00735df3d3f0"
            },
            "downloads": -1,
            "filename": "uiautomator2-3.2.8.tar.gz",
            "has_sig": false,
            "md5_digest": "dd70c61948926b9b938cd1bc2b0ca43c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 5206059,
            "upload_time": "2024-12-05T14:28:01",
            "upload_time_iso_8601": "2024-12-05T14:28:01.753030Z",
            "url": "https://files.pythonhosted.org/packages/b8/92/746aba119f556334719e0d1d9eef71c9646729585f0f9ee88567364041e9/uiautomator2-3.2.8.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-05 14:28:01",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "openatx",
    "github_project": "uiautomator2",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "uiautomator2"
}
        
Elapsed time: 0.41536s