PyAutoGUI库自动化测试脚本工具模拟键盘鼠标操作
PyAutoGUI主要用于模拟鼠标和键盘操作,支持Windows、macOS和Linux桌面环境。
其所有用法尽在此处:
import pyautogui import time def moveDemo(): print("鼠标位置:",pyautogui.position()) # 显示当前鼠标位置 screen_width, screen_height = pyautogui.size() print(f"屏幕宽度: {screen_width}, 屏幕高度: {screen_height}") pyautogui.moveTo(100, 100, duration=1) # 移动鼠标到坐标(100, 100) duration是移动所需时间(秒) pyautogui.move(100, 0, duration=1) # 从当前位置相对移动 向右移动100像素 pyautogui.moveTo(150, 150, duration=1) pyautogui.click() # 在当前位置左键单击 pyautogui.write('Hello, PyAutoGUI!') #输入文字 time.sleep(1) # 等待1秒 pyautogui.click(x=200, y=200) # 在(200, 200)处左键单击 pyautogui.rightClick(x=300, y=300) #右键点击 pyautogui.doubleClick(x=400, y=400)#双击 pyautogui.moveTo(100, 100, duration=1) pyautogui.dragTo(300, 300, duration=1, button='left') #从(100, 100)拖拽到(300, 300) pyautogui.drag(100, 0, duration=1, button='left') # 从当前位置相对拖拽 向右拖拽100像素 pyautogui.scroll(10) #向上滚动10个单位 pyautogui.scroll(-10) # 向下滚动10个单位 def clickDemo(): pyautogui.press('enter')#按下并释放一个键 ''' 支持的特殊按键名称包括 enter(回车) esc(退出) tab(制表符) alt, ctrl, shift(组合键) up, down, left, right(方向键) f1到f12(功能键) ''' pyautogui.hotkey('ctrl', 'c') # 复制 组合键 pyautogui.hotkey('ctrl', 'v') # 粘贴 组合键 #按下不释放 pyautogui.keyDown('shift') pyautogui.press('4') # 输入$ pyautogui.keyUp('shift') def imgDemo(): # 对整个屏幕进行截图 screenshot = pyautogui.screenshot() screenshot.save('我的屏幕截图.png') #对指定区域截图 region_screenshot = pyautogui.screenshot(region=(50, 50, 300, 400)) # 左上角300x400的区域 region_screenshot.save('区域截图.png') #查找屏幕上的图像位置 position = pyautogui.locateOnScreen('区域截图.png') print(f"找到图片,位置: {position}") # 获取图像的中心点 center = pyautogui.center(position) print(f"图片中心点: {center}") # 点击图像中心 pyautogui.click(center) def showdialog(): #显示一个警告框 pyautogui.alert(text='操作已完成', title ='提示', button ='OK') #确认框 response = pyautogui.confirm(text='是否继续?', title ='确认', buttons = ['是','否','取消']) print(f"用户选择了:{response}") #密码输入框 password = pyautogui.password(text='请输入密码', title ='密码', default ='', mask ='*') print(f"用户输入了:{password}") if __name__ == "__main__": #PyAutoGUI有一个安全机制,当你把鼠标快速移动到屏幕的左上角时,程序会暂停(引发异常)。这个功能是为了防止程序失控,让你有机会终止程序。可通过下面代码关闭它 pyautogui.FAILSAFE = False #全局暂停设置 pyautogui.PAUSE = 0.5 # 每次操作后暂停0.5秒 #moveDemo() #clickDemo() #imgDemo() showdialog()
-----------------------------------------------------------------