?傳統(tǒng)的基于元素定位的UI自動(dòng)化在斷言的時(shí)候都存在一個(gè)缺陷,無(wú)法像人眼一樣判斷頁(yè)面的顯示效果,雖然也可以通過(guò)文本+css+布局等方式,設(shè)置多個(gè)斷言的方式來(lái)綜合判斷,但不夠優(yōu)雅和直觀。如果有某種技術(shù)可以像人眼一樣在圖片中查找和定位圖片的位置再結(jié)合操作系統(tǒng)級(jí)別的操作(鼠標(biāo),鍵盤(pán),觸摸等等),那就可以近乎于模擬人工操作軟件實(shí)現(xiàn)自動(dòng)化。
?aircv實(shí)現(xiàn)了在圖片中查找圖片,并可以返回查找圖片相對(duì)于源圖片的位置,如果源圖片是全屏截圖,那意味著其返回的坐標(biāo)位置就是屏幕的實(shí)際坐標(biāo),再結(jié)合pyautogui可以在坐標(biāo)位置進(jìn)行鼠標(biāo)操作,在光標(biāo)位置輸入文本等操作,就可以實(shí)現(xiàn)一下UI自動(dòng)化的場(chǎng)景。實(shí)踐代碼如下:
需要登錄的界面(部分截圖)

image.png
賬號(hào)(user.png)截圖:

image.png
輸入框在賬號(hào)下面大約45個(gè)像素,因此先定位的賬號(hào)的位置,再加一個(gè)y偏移量
密碼輸入框采取類(lèi)似的定位策略
密碼(pwd.png)

image.png
登錄按鈕(login_button.png)

image.png
代碼如下:
import aircv
import pyautogui
import time
def screen(x=1920, y=1080):
"""
屏幕截圖
:param x: 橫坐標(biāo)
:param y: 縱坐標(biāo)
:return:
"""
pyautogui.screenshot('screen.png', region=(0, 0, x, y))
return 'screen.png'
def click_element(src_image, dst_image, offset_x=0, offset_y=0):
"""
基于圖像查找點(diǎn)擊
:param src_image:
:param dst_image:
:param offset_x:
:param offset_y:
:return:
"""
src_image = aircv.imread(src_image)
dst_image = aircv.imread(dst_image)
result = aircv.find_template(src_image, dst_image)
# {'result': (828.0, 597.5), 'rectangle': ((804, 582), (804, 613), (852, 582), (852, 613)), 'confidence': 1.0}
x, y = result.get('result')
if result.get('confidence') > 0.85:
pyautogui.click(x + offset_x, y + offset_y)
def input_text_pos(x, y, text):
"""
在坐標(biāo)處輸入文本
:param x:
:param y:
:param text:
:return:
"""
pyautogui.click(x, y)
pyautogui.write(text)
def input_text_image(dst_image, text, offset_x=0, offset_y=0):
src_image = screen()
click_element(src_image, dst_image, offset_x, offset_y)
pyautogui.write(text)
if __name__ == "__main__":
# 基于圖像查找圖片后點(diǎn)擊偏移位置,并輸入
input_text_image('user.png', 'abc', offset_y=45)
input_text_image('pwd.png', 'abc', offset_y=45)
# 點(diǎn)擊登錄
click_element(screen(), 'login_button.png')
定位的關(guān)鍵代碼是
src_image = aircv.imread(src_image) # 源圖片的路徑
dst_image = aircv.imread(dst_image) #目標(biāo)圖片的路徑
result = aircv.find_template(src_image, dst_image) # 返回的查找結(jié)果
# {'result': (828.0, 597.5), 'rectangle': ((804, 582), (804, 613), (852, 582), (852, 613)), 'confidence': 1.0}
# confidence 相似度大于0.85時(shí)可以認(rèn)為查找正確,根據(jù)需要做調(diào)整。result 目標(biāo)中心點(diǎn)的坐標(biāo),rectangle 目標(biāo)匹配的四個(gè)頂點(diǎn)的坐標(biāo)
獲取到位置后調(diào)用pyautogui.click(x,y)進(jìn)行點(diǎn)擊,在輸入框取得焦點(diǎn)后調(diào)用write()方法輸入文本