PyAutoGUI是一个纯Python的GUI自动化工具,其目的是可以用程序自动控制鼠标和键盘操作,多平台支持(Windows,OS X,Linux)。
安装
pip3 install pyautogui
pyautogui鼠标操作样例
import pyautogui
screenWidth, screenHeight = pyautogui.size()
currentMouseX, currentMouseY = pyautogui.position()
pyautogui.moveTo(x=100, y=100,duration=2, tween=pyautogui.linear)
pyautogui.moveTo(screenWidth / 2, screenHeight / 2)
pyautogui.click(x=None, y=None, clicks=1, interval=0.0, button='left', duration=0.0, tween=pyautogui.linear)
pyautogui.moveRel(xOffset=None, yOffset=10,duration=0.0, tween=pyautogui.linear)
pyautogui.doubleClick(x=None, y=None, interval=0.0, button='left', duration=0.0, tween=pyautogui.linear)
pyautogui.tripleClick(x=None, y=None, interval=0.0, button='left', duration=0.0, tween=pyautogui.linear)
pyautogui.rightClick()
pyautogui.middleClick()
pyautogui.moveTo(x=500, y=500, duration=2, tween=pyautogui.easeInOutQuad)
pyautogui.dragTo(x=427, y=535, duration=3,button='left')
pyautogui.dragRel(xOffset=100,yOffset=100,duration=,button='left',mouseDownUp=False)
pyautogui.mouseDown(x=1796, y=778, button='left')
pyautogui.mouseUp(x=2745, y=778, button='left',duration=5)
pyautogui.scroll()
pyautogui.hscroll()
pyautogui.vscroll()
pyautogui键盘操作样例
pyautogui.typewrite(message='Hello world!',interval=0.5)
pyautogui.press('esc')
pyautogui.keyDown('shift')
pyautogui.keyUp('shift')
pyautogui.hotkey('ctrl', 'c')
按键支持
按键 | 说明 |
---|---|
enter (或return 或 \n ) |
回车 |
esc |
ESC键 |
shiftleft , shiftright |
左右SHIFT键 |
altleft , altright |
左右ALT键 |
ctrlleft , ctrlright |
左右CTRL键 |
tab (\t ) |
TAB键 |
backspace , delete |
BACKSPACE 、DELETE键 |
pageup , pagedown |
PAGE UP 和 PAGE DOWN键 |
home , end |
HOME 和 END键 |
up , down , left ,right |
箭头键 |
f1 , f2 , f3 …. |
F1…….F12键 |
volumemute , volumedown ,volumeup |
有些键盘没有 |
pause |
PAUSE键 |
capslock , numlock ,scrolllock |
CAPS LOCK, NUM LOCK, 和 SCROLLLOCK 键 |
insert |
INS或INSERT键 |
printscreen |
PRTSC 或 PRINT SCREEN键 |
winleft , winright |
Win键 |
command |
Mac OS X command键 |
提示信息
alert
pyautogui.alert(text='This is an alert box.', title='Test')
option
pyautogui.confirm('Enter option.', buttons=['A', 'B', 'C'])
password
a = pyautogui.password('Enter password (text will be hidden)')
print(a)
prompt
a = pyautogui.prompt('input message')
print(a)
截屏
整个屏幕截图并保存
im1 = pyautogui.screenshot()
im1.save('my_screenshot.png')
im2 = pyautogui.screenshot('my_screenshot2.png')
屏幕查找图片位置并获取中间点
coords = pyautogui.locateOnScreen('folder.png')
x,y=pyautogui.center(coords)
pyautogui.rightClick(x,y)
安全设置
import pyautogui
pyautogui.FAILSAFE = True
pyautogui.PAUSE = 0.5