前期准備:
python3.6
pyautogui
pywinauto
以下代碼實現內容:
1.打開記事本
2.記事本中輸入This is a test
3.保存內容
4.退出進程
import pyautogui from pywinauto import application import time import os class Autogui(): def __init__(self): self.app=application.Application() def run(self, tool_name): self.app.start(tool_name) time.sleep(2) #defined coordinates def coordinate(self,path): try: coordinates = pyautogui.locateOnScreen(path) x, y = pyautogui.center(coordinates) return x,y except Exception as e: print('Undefined coordinates: ', e) #Abnormal judgment def onscreen(self,x,y,content1): while pyautogui.onScreen(x, y) == True: print(content1) break def moveto(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) def moverel(self,x,y): pyautogui.moveRel(x,y,1,pyautogui.easeInQuad) def leftclick(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.click(button='left') def leftclick_down(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.mouseDown(button='left') def leftclick_up(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.mouseUp(button='left') def rightclick(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.click(button='right') def middleclick(self0,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.click(button='middle') def doubleclick(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.doubleClick(button='left') def keydown(self,key): pyautogui.keyDown(key) def press(self,key): pyautogui.press(key) def keyup(self,key): pyautogui.keyUp(key) def hotkey(self,key1,key2): pyautogui.hotkey(key1,key2) if __name__=='__main__': Test=Autogui() application_path=input('Application path : ') Test.run(application_path) # Test.run('notepad.exe') time.sleep(1) source_Path='./fouce.png' source_judge_Path='./fouce_judge.png' content1='The edit operation is correct' content2='The edit operation is fail' key1='s' key2='ctrlleft' # edit try: Test.leftclick(Test.coordinate(source_Path)[0], Test.coordinate(source_Path)[1]) pyautogui.typewrite('This is a test',0.1) time.sleep(0.5) Test.onscreen(Test.coordinate(source_judge_Path)[0], Test.coordinate(source_judge_Path)[1], content1) except Exception as e: print(content2 + ': ', e) # save try: time.sleep(2) Test.hotkey(key2, key1) time.sleep(0.5) print('The save operation is correct') except Exception as e: print('Save Error: ', e) try: time.sleep(2) os.system('taskkill /F /IM notepad.exe') except Exception as e: print('Exit Error: ',e) input()
貼上代碼中兩張圖片,fouce.png 用來將光標定位到輸入區域,fouce_judge.png 用來跟實際結果做對比,判斷實際結果是否正確
fouce.png
fouce_judge.png
pyautogui自動化腳本優點
1.不用擔心因為分辨率的改變導致腳本失效
2.完全自定義日志輸出
3.真UI自動化,可以判斷每一步UI是否正確