python UIAutomator2使用超詳細(xì)教程
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ī)上都安裝uiautomator2python -m uiautomator2 init # 指定手機(jī)安裝uiautomator2, 用 --mirrorpython -m uiautomator2 init --mirror --serial $SERIAL# 嫌棄慢的話,可以用國內(nèi)的鏡像python -m uiautomator2 init --mirror
最后提示success,代表atx-agent初始化成功。
3、安裝weditor有了這個,方便我們快速的識別手機(jī)上的元素,方便寫代碼
pip install -U weditor
安裝好之后,就可以在命令行運(yùn)行 weditor --help 確認(rèn)是否安裝成功了。
Windows系統(tǒng)可以使用命令在桌面創(chuàng)建一個快捷方式:
weditor --shortcut
在windows cmd中執(zhí)行上述命令后,會在桌面上創(chuàng)建一個快捷方式,如下圖:
啟動方法:
方法1.命令行直接輸入 weditor 會自動打開瀏覽器,輸入設(shè)備的ip或者序列號,點(diǎn)擊Connect即可;方法2.桌面上雙擊WEditor快捷方式即可;方法3.命令行中執(zhí)行 python -m weditor
啟動后如下圖:
調(diào)用uiautomator2的過程
配置手機(jī)設(shè)備參數(shù),設(shè)置具體操作的是哪一臺手機(jī)抓取手機(jī)上應(yīng)用的控件,制定對應(yīng)的控件來進(jìn)行操作對抓取到的控件進(jìn)行操作,比如點(diǎn)擊、填寫參數(shù)等。
設(shè)備連接方法,有兩種:
python-uiautomator2連接手機(jī)的方式有兩種,一種是通過WIFI,另外一種是通過USB。兩種方法各有優(yōu)缺點(diǎn)。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 u2d = u2.connect(’192.168.0.107’)
(2)通過USB, 假設(shè)設(shè)備序列是123456789F
import uiautomator2 as u2d = 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ì)算機(jī)。
檢查并維持設(shè)備端守護(hù)進(jìn)程處于運(yùn)行狀態(tài):
d.healthcheck()
打開調(diào)試開關(guān):
d.debug = Trued.info
安裝應(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ùn)行的應(yīng)用程序:
# 停止所有d.app_stop_all()# 停止所有應(yīng)用程序,除了com.examples.demod.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 IPprint(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 fileobjwith 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') # 點(diǎn)擊home鍵d.press('back') # 點(diǎn)擊back鍵d.press('left') # 點(diǎn)擊左鍵d.press('right') # 點(diǎn)擊右鍵d.press('up') # 點(diǎn)擊上鍵d.press('down') # 點(diǎn)擊下鍵d.press('center') # 點(diǎn)擊選中d.press('menu') # 點(diǎn)擊menu按鍵d.press('search') # 點(diǎn)擊搜索按鍵d.press('enter') # 點(diǎn)擊enter鍵d.press('delete') # 點(diǎn)擊刪除按鍵d.press('recent') # 點(diǎn)擊近期活動按鍵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為點(diǎn)擊坐標(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)# 滑動點(diǎn) 多用于九宮格解鎖,提前獲取到每個點(diǎn)的相對坐標(biāo)(這里支持百分比)# 從點(diǎn)(x0, y0)滑到點(diǎn)(x1, y1)再滑到點(diǎn)(x2, y2)# 兩點(diǎn)之間的滑動速度是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格式的圖像. 但你必須先安裝pillowimage = d.screenshot() # default format='pillow'image.save('home.jpg') # 或’home.png’,目前只支持png 和 jpg格式的圖像 # 得到OpenCV的格式圖像。當(dāng)然,你需要numpy和cv2安裝第一個import cv2image = 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,否則為Falsed.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中心點(diǎn)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('//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秒時點(diǎn)擊,默認(rèn)的超時0d(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# 點(diǎn)擊基準(zhǔn)位置偏移d(text='Settings').click(offset=(0.5, 0.5)) # 點(diǎn)擊中心位置,同d(text='Settings').click()d(text='Settings').click(offset=(0, 0)) # 點(diǎn)擊左前位置d(text='Settings').click(offset=(1, 1)) # 點(diǎn)擊右下# 執(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對象拖向另一個點(diǎn)或另一個UI對象# Android<4.3不能使用drag.# 在0.5秒內(nèi)將UI對象拖到屏幕點(diǎn)(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)
常見用法:
# 等待10sd.xpath('//android.widget.TextView').wait(10.0)# 找到并單擊d.xpath('//*[@content-desc=’分享’]').click()# 檢查是否存在if d.xpath('//android.widget.TextView[contains(@text, ’Se’)]').exists: print('exists') # 獲取所有文本視圖文本、屬性和中心點(diǎn)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) #獲取屬性和中心點(diǎn)#返回: (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/
到此這篇關(guān)于python UIAutomator2使用超詳細(xì)教程的文章就介紹到這了,更多相關(guān)python UIAutomator2使用內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Django ORM實(shí)現(xiàn)按天獲取數(shù)據(jù)去重求和例子2. Jsp中request的3個基礎(chǔ)實(shí)踐3. XML入門的常見問題(一)4. jsp EL表達(dá)式詳解5. 解決ajax的delete、put方法接收不到參數(shù)的問題方法6. IntelliJ IDEA 統(tǒng)一設(shè)置編碼為utf-8編碼的實(shí)現(xiàn)7. idea修改背景顏色樣式的方法8. chat.asp聊天程序的編寫方法9. IntelliJ IDEA設(shè)置自動提示功能快捷鍵的方法10. 怎樣才能用js生成xmldom對象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?
