目錄
- 一、環(huán)境要求
- 二、介紹
- 三、庫地址
- 四、安裝
- 五、應(yīng)用及操作
一、環(huán)境要求
python 3.6+
android 4.4+
二、介紹
uiautomator2 是一個可以使用Python對Android設(shè)備進(jìn)行UI自動化的庫。其底層基于Google uiautomator,Google提供的uiautomator庫可以獲取屏幕上任意一個APP的任意一個控件屬性,并對其進(jìn)行任意操作。
三、庫地址
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、設(shè)備安裝atx-agent
首先設(shè)備連接到PC,并能夠adb devices發(fā)現(xiàn)該設(shè)備。
執(zhí)行下面的命令會自動安裝本庫所需要的設(shè)備端程序:uiautomator-server,atx-agent,openstf / minicap,openstf / minitouch
# init就是所有USB連接電腦的手機(jī)上都安裝uiautomator2
python -m uiautomator2 init
# 指定手機(jī)安裝uiautomator2, 用 --mirror
python -m uiautomator2 init --mirror --serial $SERIAL
# 嫌棄慢的話,可以用國內(nèi)的鏡像
python -m uiautomator2 init --mirror
最后提示success,代表atx-agent初始化成功。
3、安裝weditor
有了這個,方便我們快速的識別手機(jī)上的元素,方便寫代碼
安裝好之后,就可以在命令行運行 weditor --help 確認(rèn)是否安裝成功了。
Windows系統(tǒng)可以使用命令在桌面創(chuàng)建一個快捷方式:
在windows cmd中執(zhí)行上述命令后,會在桌面上創(chuàng)建一個快捷方式,如下圖:
啟動方法:
方法1.命令行直接輸入 weditor 會自動打開瀏覽器,輸入設(shè)備的ip或者序列號,點擊Connect即可;
方法2.桌面上雙擊WEditor快捷方式即可;
方法3.命令行中執(zhí)行 python -m weditor
啟動后如下圖:
五、應(yīng)用及操作
調(diào)用uiautomator2的過程
配置手機(jī)設(shè)備參數(shù),設(shè)置具體操作的是哪一臺手機(jī)
抓取手機(jī)上應(yīng)用的控件,制定對應(yīng)的控件來進(jìn)行操作
對抓取到的控件進(jìn)行操作,比如點擊、填寫參數(shù)等。
設(shè)備連接方法,有兩種:
python-uiautomator2連接手機(jī)的方式有兩種,一種是通過WIFI,另外一種是通過USB。兩種方法各有優(yōu)缺點。
WIFI最便利的地方要數(shù)可以不用連接數(shù)據(jù)線,USB則可以用在PC和手機(jī)網(wǎng)絡(luò)不在一個網(wǎng)段用不了的情況。
(1)通過WiFi,假設(shè)設(shè)備IP 192.168.0.107和您的PC在同一網(wǎng)絡(luò)中
import uiautomator2 as u2
d = u2.connect('192.168.0.107')
(2)通過USB, 假設(shè)設(shè)備序列是123456789F
import uiautomator2 as u2
d = u2.connect('123456789F') # USB鏈接設(shè)備。或者u2.connect_usb('123456f')
#d = u2.connect_usb() 或者 d = u2.connect() ,當(dāng)前只有一個設(shè)備時可以用這個
在沒有參數(shù)的情況下調(diào)用u2.connect(), uiautomator2將從環(huán)境變量ANDROID_DEVICE_IP獲取設(shè)備IP。如果這個環(huán)境變量是空的,uiautomator將返回connect_usb,您需要確保只有一個設(shè)備連接到計算機(jī)。
檢查并維持設(shè)備端守護(hù)進(jìn)程處于運行狀態(tài):
打開調(diào)試開關(guān):
安裝應(yīng)用,只能從URL安裝:
d.app_install('http://some-domain.com/some.apk') #引號內(nèi)為下載apk地址
啟動應(yīng)用:
d.app_start('com.eg.android.AlipayGphone') #引號內(nèi)為包名稱,這里為支付寶
停止應(yīng)用:
#相當(dāng)于'am force-stop'強(qiáng)制停止應(yīng)用
d.app_stop('com.eg.android.AlipayGphone')
#相當(dāng)于'pm clear' 清空App數(shù)據(jù)
d.app_clear('com.eg.android.AlipayGphone')
停止所有正在運行的應(yīng)用程序:
# 停止所有
d.app_stop_all()
# 停止所有應(yīng)用程序,除了com.examples.demo
d.app_stop_all(excludes=['com.examples.demo'])
跳過彈窗,禁止彈窗:
d.disable_popups() # 自動跳過彈出窗口
d.disable_popups(False) # 禁用自動跳過彈出窗
獲取設(shè)備信息:
# 獲取基本信息
d.info
# 獲取窗口大小
print(d.window_size())
# 設(shè)備垂直輸出示例: (1080, 1920)
# 設(shè)備水平輸出示例: (1920, 1080)
# 獲取當(dāng)前應(yīng)用程序信息。對于某些android設(shè)備,輸出可以為空
print(d.current_app())
#獲取設(shè)備序列號
print(d.serial)
#獲取WIFI IP
print(d.wlan_ip)
#獲取詳細(xì)的設(shè)備信息
print(d.device_info)
獲取應(yīng)用信息:
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
}
'''
# 保存應(yīng)用程序圖標(biāo)
img = d.app_icon("com.eg.android.AlipayGphone")
img.save("icon.png")
推拉文件:
(1)將文件推送到設(shè)備
# 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)從設(shè)備中拉出一個文件
d.pull("/sdcard/tmp.txt", "tmp.txt")
# 如果在設(shè)備上找不到文件,F(xiàn)ileNotFoundError將引發(fā)
d.pull("/sdcard/some-file-not-exists.txt", "tmp.txt")
關(guān)鍵事件:
(1)打開/關(guān)閉屏幕
d.screen_on()#打開屏幕
d.screen_off() #關(guān)閉屏幕
(2)獲取當(dāng)前屏幕狀態(tài)
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") # 相機(jī)
d.press("power") #電源鍵
(4)解鎖屏幕
d.unlock()
# 相當(dāng)于
# 1. 發(fā)射活動:com.github.uiautomator.ACTION_IDENTIFY
# 2. 按home鍵
手勢與設(shè)備的交互:
# 單擊屏幕
d.click(x,y) # x,y為點擊坐標(biāo)
# 雙擊屏幕
d.double_click(x,y)
d.double_click(x,y,0.1) # 默認(rèn)兩個單擊之間間隔時間為0.1秒
# 長按
d.long_click(x,y)
d.long_click(x,y,0.5) # 長按0.5秒(默認(rèn))
# 滑動
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)
# 滑動點 多用于九宮格解鎖,提前獲取到每個點的相對坐標(biāo)(這里支持百分比)
# 從點(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"
# 設(shè)置方向
d.set_orientation("l") # or "left"
d.set_orientation("r") # or "right"
d.set_orientation("n") # or "natural"
#凍結(jié)/ 開啟旋轉(zhuǎn)
d.freeze_rotation() # 凍結(jié)旋轉(zhuǎn)
d.freeze_rotation(False) # 開啟旋轉(zhuǎn)
########## 截圖 ############
# 截圖并保存到電腦上的一個文件中,需要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的格式圖像。當(dāng)然,你需要numpy和cv2安裝第一個
import cv2
image = d.screenshot(format='opencv')
cv2.imwrite('home.jpg', image)
# 獲取原始JPEG數(shù)據(jù)
imagebin = d.screenshot(format='raw')
open("some.jpg", "wb").write(imagebin)
#############################
# 轉(zhuǎn)儲UI層次結(jié)構(gòu)
# get the UI hierarchy dump content (unicoded).(獲取UI層次結(jié)構(gòu)轉(zhuǎn)儲內(nèi)容)
d.dump_hierarchy()
# 打開通知或快速設(shè)置
d.open_notification() #下拉打開通知欄
d.open_quick_settings() #下拉打開快速設(shè)置欄
# 檢查特定的UI對象是否存在
d(text="Settings").exists # 返回布爾值,如果存在則為True,否則為False
d.exists(text="Settings") # 另一種寫法
# 高級用法
d(text="Settings").exists(timeout=3) # 等待'Settings'在3秒鐘出現(xiàn)
# 獲取特定UI對象的信息
d(text="Settings").info
# 獲取/設(shè)置/清除可編輯字段的文本(例如EditText小部件)
d(text="Settings").get_text() #得到文本小部件
d(text="Settings").set_text("My text...") #設(shè)置文本
d(text="Settings").clear_text() #清除文本
# 獲取Widget中心點
d(text="Settings").center()
#d(text="Settings").center(offset=(0, 0)) # 基準(zhǔn)位置左前
UI對象有五種定位方式:
# text、resourceId、description、className、xpath、坐標(biāo)
# 執(zhí)行單擊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="設(shè)置").click()
d(description="設(shè)置", className="android.widget.TextView").click()
#className定位單擊
d(className="android.widget.TextView").click()
#xpath定位單擊
d.xpath("http://android.widget.FrameLayout[@index='0']/android.widget.LinearLayout[@index='0']").click()
#坐標(biāo)單擊
d.click(182, 1264)
# 等待元素出現(xiàn)(最多10秒),出現(xiàn)后單擊
d(text="Settings").click(timeout=10)
# 在10秒時點擊,默認(rèn)的超時0
d(text='Skip').click_exists(timeout=10.0)
# 單擊直到元素消失,返回布爾
d(text="Skip").click_gone(maxretry=10, interval=1.0) # maxretry默認(rèn)值10,interval默認(rèn)值1.0
# 點擊基準(zhǔn)位置偏移
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)) # 點擊右下
# 執(zhí)行雙擊UI對象
d(text="設(shè)置").double_click() # 雙擊特定ui對象的中心
d.double_click(x, y, 0.1) # 兩次單擊之間的默認(rèn)持續(xù)時間為0.1秒
#執(zhí)行長按UI對象
# 長按特定UI對象的中心
d(text="Settings").long_click()
d.long_click(x, y, 0.5) # 長按坐標(biāo)位置0.5s默認(rèn)
# 將UI對象拖向另一個點或另一個UI對象
# Android4.3不能使用drag.
# 在0.5秒內(nèi)將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("http://android.widget.TextView").wait(10.0)
# 找到并單擊
d.xpath("http://*[@content-desc='分享']").click()
# 檢查是否存在
if d.xpath("http://android.widget.TextView[contains(@text, 'Se')]").exists:
print("exists")
# 獲取所有文本視圖文本、屬性和中心點
for elem in d.xpath("http://android.widget.TextView").all():
print("Text:", elem.text)
#獲取視圖文本
for elem in d.xpath("http://android.widget.TextView").all():
print("Attrib:", elem.attrib)
#獲取屬性和中心點
#返回: (100, 200)
for elem in d.xpath("http://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/
到此這篇關(guān)于python UIAutomator2使用超詳細(xì)教程的文章就介紹到這了,更多相關(guān)python UIAutomator2使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python 使用uiautomator2連接手機(jī)設(shè)備的實現(xiàn)
- Python+uiautomator2實現(xiàn)自動刷抖音視頻功能
- 詳解python uiautomator2 watcher的使用方法
- 利用Python批量提取Win10鎖屏壁紙實戰(zhàn)教程
- Python中Selenium模擬JQuery滑動解鎖實例
- Python+uiautomator2實現(xiàn)手機(jī)鎖屏解鎖功能