1. 启动自动防故障功能
# 设置调用函数后停顿2s;启动自动防故障功能(将鼠标移到左上raise FailSafeException)
pyautogui.PAUSE=2
pyautogui.FAILSAFE=True
2. 鼠标位置
>>> pyautogui.size()
(1600, 900)
>>> pyautogui.position()
(466, 660)
>>> pyautogui.position()
(1153, 469)
3. 鼠标移动
def mt():
"""根据屏幕坐标移动"""
for i in range(0,10):
pyautogui.moveTo(100,100,duration=0.5)
pyautogui.moveTo(500,100,duration=0.5)
pyautogui.moveTo(500,300,duration=0.5)
pyautogui.moveTo(100,300,duration=0.5)
def mr():
"""相对移动(鼠标坐标)"""
for i in range(0,10):
# 相对当前鼠标位置移动
pyautogui.moveRel(20,0,duration=0.5)
pyautogui.moveRel(0,20,duration=0.5)
pyautogui.moveRel(-20,0,duration=0.5)
pyautogui.moveRel(0,-20,duration=0.5)
4. 鼠标拖拽移动
鼠标移动相当于我们移动鼠标,没有其它操作。鼠标拖拽移动相当于按住鼠标左键移动。
下面示例需要借助画图工具
def drawRangle(distance):
"""画一个矩形"""
time.sleep(3)
pyautogui.dragRel(0,distance,duration=0.5)
pyautogui.dragRel(distance,0,duration=0.5)
pyautogui.dragRel(0, -distance, duration=0.5)
pyautogui.dragRel(-distance, 0, duration=0.5)
def drawNum():
time.sleep(5) # 有足够的时间将鼠标移到画图内
num=200
while num>0:
drawRangle(num)
pyautogui.moveRel(5,5,duration=0.5)
num-=10
save_screen()
def drawLine(distance):
"""画线"""
pyautogui.dragRel(distance,0)
pyautogui.dragRel(0,distance)
pyautogui.dragRel(-(distance-5),0)
pyautogui.dragRel(0,-(distance-5))
def drawLineNum():
time.sleep(5) # 有足够的时间将鼠标移到画图内
num=200
while num>0:
drawLine(num)
num-=10
save_screen()
def save_screen():
x, y = pyautogui.position()
print(x, y)
region = (x-300, y-300, x+300, y+300)
pyautogui.screenshot(imageFilename=r'e:\path\screen.png', region=region)
5. 键盘输入
>>> def t():
time.sleep(3)
pyautogui.typewrite('hello world')
键盘热键
pyautogui.click(100,200)
for i in range(0,10):
pyautogui.hotkey('ctrl','a')
pyautogui.hotkey('ctrl','c')
# 单个按键键入
# pyautogui.press('right')
# pyautogui.press('enter')
# 可一组按键键入
pyautogui.typewrite(['right','enter'])
pyautogui.hotkey('ctrl','v')