pyautogui學習1:基礎功能

之前使用pywinauto來做UI自動化,其中也有鼠標鍵盤的操作,但是使用不是很方便。

所以查看了一下,發現pyautogui這個庫,研究了一下,覺得這個庫操作鼠標鍵盤比較方便。

看了官方文檔,把基本的操作在此做個記錄:

>>> import pyautogui
>>> pyautogui.position()  # 當前鼠標的座標
(968, 56)
>>> pyautogui.size()  # 當前屏幕的大小,及分辨率
(1920, 1080)
>>> pyautogui.onScreen(x, y)  # 如果x和y表示的座標在屏幕範圍內則返回True
True

鼠標功能:

>>> pyautogui.moveTo(x, y, duration=num_seconds)  # 移動鼠標至xy座標,duration是在多少秒內移動到xy座標(這是絕對座標),如果duration=0,或者不寫就是直接移動到xy座標處
>>> pyautogui.moveRel(xOffset, yOffset, duration=num_seconds)  # 相對移動x和y,此處可以用move來替代moveRel
>>> pyautogui.dragTo(x, y, duration=num_seconds)  # 拖動鼠標至xy座標
>>> pyautogui.dragRel(xOffset, yOffset, duration=num_seconds)  # 拖動鼠標x和y
>>> pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks, button='left') # 左鍵點擊
>>> pyautogui.rightClick(x=moveToX, y=moveToY)    # 右擊    x和y是指在xy座標處點擊
>>> pyautogui.middleClick(x=moveToX, y=moveToY)    # 點擊中鍵
>>> pyautogui.doubleClick(x=moveToX, y=moveToY)    # 雙擊左鍵
>>> pyautogui.tripleClick(x=moveToX, y=moveToY)    # 三擊左鍵
>>> pyautogui.scroll(amount_to_scroll, x=moveToX, y=moveToY) # 滾動滾輪

pyautogui.scroll(100)    # 正數爲向上滾動
pyautogui.scroll(-100)    # 負數爲向下滾動
>>> pyautogui.mouseDown(x=moveToX, y=moveToY, button='left')    # 鼠標按下
>>> pyautogui.mouseUp(x=moveToX, y=moveToY, button='left')    # 鼠標放開

 

鍵盤功能:

>>> pyautogui.typewrite('Hello world!\n', interval=secs_between_keys)  # 輸入Hello world!
>>> pyautogui.hotkey('ctrl', 'c')  # ctrl-c
>>> pyautogui.hotkey('ctrl', 'v')  # ctrl-v
>>> pyautogui.keyDown(key_name)    # 單獨按下一個鍵
>>> pyautogui.keyUp(key_name)    # 單獨放開一個鍵

消息對話框功能:

>>> pyautogui.alert('This displays some text with an OK button.')
>>> pyautogui.confirm('This displays text and has an OK and Cancel button.')
'OK'
>>> pyautogui.prompt('This lets the user type in a string and press OK.')
'This is what I typed in.'

 

截屏功能:

>>> pyautogui.screenshot('foo.png')  # 全屏截圖,保存爲foo.png放在當前文件目錄下
# 在界面上如果找不到圖片,返回None。找到圖片,返回(634,438)是圖片左上角的座標,後面是寬度和高度
>>> pyautogui.locateOnScreen('123.png') 
Box(left=634, top=438, width=120, height=123)


# 返回圖片中心的座標
>>> pyautogui.locateCenterOnScreen('looksLikeThis.png') 
(898, 423)
# 返回屏幕所以找到的圖片的位置的生成器
>>> for i in pyautogui.locateAllOnScreen('looksLikeThis.png')
...
...
(863, 117, 70, 13)
(623, 137, 70, 13)
(853, 577, 70, 13)
(883, 617, 70, 13)
(973, 657, 70, 13)
(933, 877, 70, 13)

>>> list(pyautogui.locateAllOnScreen('looksLikeThis.png'))
[(863, 117, 70, 13), (623, 137, 70, 13), (853, 577, 70, 13), (883, 617, 70, 13), (973, 657, 70, 13), (933, 877, 70, 13)]

 

發佈了215 篇原創文章 · 獲贊 9 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章