python UIAutomator2使用超詳細教程

一、環境要求

python 3.6+
android 4.4+

二、介紹

uiautomator2 是一個可以使用Python對Android設備進行UI自動化的庫。其底層基於Google uiautomator,Google提供的uiautomator庫可以獲取屏幕上任意一個APP的任意一個控件屬性,並對其進行任意操作。

三、庫地址

GitHub地址:
https://github.com/openatx/uiautomator2

https://github.com/openatx/uiautomator2/blob/master/README.md

四、安裝

1、安裝uiautomator2

pip install --pre uiautomator2 
pip install pillow (如果需要截圖,可安裝這個庫)

2、設備安裝atx-agent

首先設備連接到PC,並能夠adb devices發現該設備。
執行下面的命令會自動安裝本庫所需要的設備端程序:uiautomator-server,atx-agent,openstf / minicap,openstf / minitouch

# init就是所有USB連接電腦的手機上都安裝uiautomator2
python -m uiautomator2 init
 
# 指定手機安裝uiautomator2, 用 --mirror
python -m uiautomator2 init --mirror --serial $SERIAL

# 嫌棄慢的話,可以用國內的鏡像
python -m uiautomator2 init --mirror

最後提示success,代表atx-agent初始化成功。

3、安裝weditor
有瞭這個,方便我們快速的識別手機上的元素,方便寫代碼

pip install -U weditor

安裝好之後,就可以在命令行運行 weditor –help 確認是否安裝成功瞭。

Windows系統可以使用命令在桌面創建一個快捷方式:

weditor --shortcut

在windows cmd中執行上述命令後,會在桌面上創建一個快捷方式,如下圖:

在這裡插入圖片描述

啟動方法:

方法1.命令行直接輸入 weditor 會自動打開瀏覽器,輸入設備的ip或者序列號,點擊Connect即可;
方法2.桌面上雙擊WEditor快捷方式即可;
方法3.命令行中執行 python -m weditor

啟動後如下圖:

在這裡插入圖片描述

五、應用及操作

調用uiautomator2的過程

配置手機設備參數,設置具體操作的是哪一臺手機
抓取手機上應用的控件,制定對應的控件來進行操作
對抓取到的控件進行操作,比如點擊、填寫參數等。

設備連接方法,有兩種

python-uiautomator2連接手機的方式有兩種,一種是通過WIFI,另外一種是通過USB。兩種方法各有優缺點。
WIFI最便利的地方要數可以不用連接數據線,USB則可以用在PC和手機網絡不在一個網段用不瞭的情況。

(1)通過WiFi,假設設備IP 192.168.0.107和您的PC在同一網絡中

import uiautomator2 as u2
d = u2.connect('192.168.0.107') 

(2)通過USB, 假設設備序列是123456789F

import uiautomator2 as u2
d = u2.connect('123456789F') # USB鏈接設備。或者u2.connect_usb('123456f')
#d = u2.connect_usb() 或者 d = u2.connect() ,當前隻有一個設備時可以用這個

在沒有參數的情況下調用u2.connect(), uiautomator2將從環境變量ANDROID_DEVICE_IP獲取設備IP。如果這個環境變量是空的,uiautomator將返回connect_usb,您需要確保隻有一個設備連接到計算機。

檢查並維持設備端守護進程處於運行狀態:

d.healthcheck()

打開調試開關:

d.debug = True
d.info

安裝應用,隻能從URL安裝:

d.app_install('http://some-domain.com/some.apk') #引號內為下載apk地址

啟動應用:

d.app_start('com.eg.android.AlipayGphone') #引號內為包名稱,這裡為支付寶

停止應用:

#相當於'am force-stop'強制停止應用
d.app_stop('com.eg.android.AlipayGphone') 

#相當於'pm clear' 清空App數據
d.app_clear('com.eg.android.AlipayGphone')

停止所有正在運行的應用程序:

# 停止所有
d.app_stop_all()

# 停止所有應用程序,除瞭com.examples.demo
d.app_stop_all(excludes=['com.examples.demo'])

跳過彈窗,禁止彈窗:

d.disable_popups() # 自動跳過彈出窗口 
d.disable_popups(False) # 禁用自動跳過彈出窗

獲取設備信息:

# 獲取基本信息
d.info

# 獲取窗口大小
print(d.window_size())
# 設備垂直輸出示例: (1080, 1920)
# 設備水平輸出示例: (1920, 1080)

# 獲取當前應用程序信息。對於某些android設備,輸出可以為空
print(d.current_app())

#獲取設備序列號
print(d.serial)

#獲取WIFI IP
print(d.wlan_ip)

#獲取詳細的設備信息
print(d.device_info)

獲取應用信息:

d.app_info("com.eg.android.AlipayGphone")
# 會輸出
'''
{
 "packageName": "com.eg.android.AlipayGphone", 
 "mainActivity": "com.eg.android.AlipayGphone.AlipayLogin", 
 "label": "支付寶", 
 "versionName": "10.2.13.9020", 
 "versionCode": 360, 
 "size": 108306104
}
'''
# 保存應用程序圖標
img = d.app_icon("com.eg.android.AlipayGphone")
img.save("icon.png")

推拉文件:
(1)將文件推送到設備

# push文件夾
d.push("foo.txt", "/sdcard/")
# push和重命名
d.push("foo.txt", "/sdcard/bar.txt")
# push fileobj
with open("foo.txt", 'rb') as f:
 d.push(f, "/sdcard/")
# 推動和更改文件訪問模式
d.push("foo.sh", "/data/local/tmp/", mode=0o755)

(2)從設備中拉出一個文件

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

# 如果在設備上找不到文件,FileNotFoundError將引發
d.pull("/sdcard/some-file-not-exists.txt", "tmp.txt")

關鍵事件:
(1)打開/關閉屏幕

d.screen_on()#打開屏幕 
d.screen_off() #關閉屏幕

(2)獲取當前屏幕狀態

d.info.get('screenOn') # 需要 Android> = 4.4

(3)硬鍵盤和軟鍵盤操作

d.press("home") # 點擊home鍵
d.press("back") # 點擊back鍵
d.press("left") # 點擊左鍵
d.press("right") # 點擊右鍵
d.press("up") # 點擊上鍵
d.press("down") # 點擊下鍵
d.press("center") # 點擊選中
d.press("menu") # 點擊menu按鍵
d.press("search") # 點擊搜索按鍵
d.press("enter") # 點擊enter鍵
d.press("delete") # 點擊刪除按鍵
d.press("recent") # 點擊近期活動按鍵
d.press("volume_up") # 音量+
d.press("volume_down") # 音量-
d.press("volume_mute") # 靜音
d.press("camera") # 相機
d.press("power") #電源鍵

(4)解鎖屏幕

d.unlock()
# 相當於
# 1. 發射活動:com.github.uiautomator.ACTION_IDENTIFY
# 2. 按home鍵

手勢與設備的交互:

# 單擊屏幕
d.click(x,y) # x,y為點擊坐標

# 雙擊屏幕
d.double_click(x,y)
d.double_click(x,y,0.1) # 默認兩個單擊之間間隔時間為0.1秒

# 長按
d.long_click(x,y)
d.long_click(x,y,0.5) # 長按0.5秒(默認)

# 滑動
d.swipe(sx, sy, ex, ey)
d.swipe(sx, sy, ex, ey, 0.5) #滑動0.5s(default)

#拖動
d.drag(sx, sy, ex, ey)
d.drag(sx, sy, ex, ey, 0.5)#拖動0.5s(default)
# 滑動點 多用於九宮格解鎖,提前獲取到每個點的相對坐標(這裡支持百分比)

# 從點(x0, y0)滑到點(x1, y1)再滑到點(x2, y2)
# 兩點之間的滑動速度是0.2秒
d.swipe((x0, y0), (x1, y1), (x2, y2), 0.2)
# 註意:單擊,滑動,拖動操作支持百分比位置值。例:
d.long_click(0.5, 0.5) 表示長按屏幕中心

XPath:

# 檢索方向
d.orientation
# 檢索方向。輸出可以是 "natural" or "left" or "right" or "upsidedown"

# 設置方向
d.set_orientation("l") # or "left"
d.set_orientation("r") # or "right"
d.set_orientation("n") # or "natural"

#凍結/ 開啟旋轉
d.freeze_rotation() # 凍結旋轉
d.freeze_rotation(False) # 開啟旋轉

########## 截圖 ############
# 截圖並保存到電腦上的一個文件中,需要Android>=4.2。
d.screenshot("home.jpg")
 
# 得到PIL.Image格式的圖像. 但你必須先安裝pillow
image = d.screenshot() # default format="pillow"
image.save("home.jpg") # 或'home.png',目前隻支持png 和 jpg格式的圖像
 
# 得到OpenCV的格式圖像。當然,你需要numpy和cv2安裝第一個
import cv2
image = d.screenshot(format='opencv')
cv2.imwrite('home.jpg', image)
 
# 獲取原始JPEG數據
imagebin = d.screenshot(format='raw')
open("some.jpg", "wb").write(imagebin)

#############################

# 轉儲UI層次結構
# get the UI hierarchy dump content (unicoded).(獲取UI層次結構轉儲內容)
d.dump_hierarchy()


# 打開通知或快速設置
d.open_notification() #下拉打開通知欄
d.open_quick_settings() #下拉打開快速設置欄

# 檢查特定的UI對象是否存在
d(text="Settings").exists # 返回佈爾值,如果存在則為True,否則為False
d.exists(text="Settings") # 另一種寫法
# 高級用法
d(text="Settings").exists(timeout=3) # 等待'Settings'在3秒鐘出現

# 獲取特定UI對象的信息
d(text="Settings").info

# 獲取/設置/清除可編輯字段的文本(例如EditText小部件)
d(text="Settings").get_text() #得到文本小部件
d(text="Settings").set_text("My text...") #設置文本
d(text="Settings").clear_text() #清除文本

# 獲取Widget中心點
d(text="Settings").center()
#d(text="Settings").center(offset=(0, 0)) # 基準位置左前

UI對象有五種定位方式:

# text、resourceId、description、className、xpath、坐標

# 執行單擊UI對象
#text定位單擊
d(text="Settings").click()
d(text="Settings", className="android.widget.TextView").click()

#resourceId定位單擊
d(resourceId="com.ruguoapp.jike:id/tv_title", className="android.widget.TextView").click() 

#description定位單擊
d(description="設置").click()
d(description="設置", className="android.widget.TextView").click()

#className定位單擊
d(className="android.widget.TextView").click()

#xpath定位單擊
d.xpath("//android.widget.FrameLayout[@index='0']/android.widget.LinearLayout[@index='0']").click()

#坐標單擊
d.click(182, 1264)

# 等待元素出現(最多10秒),出現後單擊 
d(text="Settings").click(timeout=10)
# 在10秒時點擊,默認的超時0
d(text='Skip').click_exists(timeout=10.0)
# 單擊直到元素消失,返回佈爾
d(text="Skip").click_gone(maxretry=10, interval=1.0) # maxretry默認值10,interval默認值1.0
# 點擊基準位置偏移
d(text="Settings").click(offset=(0.5, 0.5)) # 點擊中心位置,同d(text="Settings").click()
d(text="Settings").click(offset=(0, 0)) # 點擊左前位置
d(text="Settings").click(offset=(1, 1)) # 點擊右下

# 執行雙擊UI對象
d(text="設置").double_click() # 雙擊特定ui對象的中心
d.double_click(x, y, 0.1) # 兩次單擊之間的默認持續時間為0.1秒

#執行長按UI對象
# 長按特定UI對象的中心
d(text="Settings").long_click()
d.long_click(x, y, 0.5) # 長按坐標位置0.5s默認

# 將UI對象拖向另一個點或另一個UI對象
# Android<4.3不能使用drag.
# 在0.5秒內將UI對象拖到屏幕點(x, y)
d(text="Settings").drag_to(x, y, duration=0.5)

# 將UI對象拖到另一個UI對象的中心位置,時間為0.25秒
d(text="Settings").drag_to(text="Clock", duration=0.25)

常見用法:

# 等待10s
d.xpath("//android.widget.TextView").wait(10.0)

# 找到並單擊
d.xpath("//*[@content-desc='分享']").click()

# 檢查是否存在
if d.xpath("//android.widget.TextView[contains(@text, 'Se')]").exists:
 print("exists")
 
# 獲取所有文本視圖文本、屬性和中心點
for elem in d.xpath("//android.widget.TextView").all():
 print("Text:", elem.text)
 
#獲取視圖文本
for elem in d.xpath("//android.widget.TextView").all():
 print("Attrib:", elem.attrib)
 
#獲取屬性和中心點
#返回: (100, 200)
for elem in d.xpath("//android.widget.TextView").all():
 print("Position:", elem.center())

# xpath常見用法:
# 所有元素
//*

# resource-id包含login字符
//*[contains(@resource-id, 'login')]

# 按鈕包含賬號或帳號
//android.widget.Button[contains(@text, '賬號') or contains(@text, '帳號')]

# 所有ImageView中的第二個
(//android.widget.ImageView)[2]

# 所有ImageView中的最後一個
(//android.widget.ImageView)[last()]

# className包含ImageView
//*[contains(name(), "ImageView")]

文章參考:https://vic.kim/2019/05/20/UIAutomator2%E7%9A%84%E4%BD%BF%E7%94%A8/

到此這篇關於python UIAutomator2使用超詳細教程的文章就介紹到這瞭,更多相關python UIAutomator2使用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: