1.安装
mac 使用pyautogui库 需要安装库:opencv-contrib-python,3.4.2.17版本可正常使用
pip install opencv-contrib-python==3.4.2.17
pip install PyAutoGUI
windows 使用pyautogui库 需要安装:
pip install -i https://pypi.doubanio.com/simple/ opencv-python==3.4.2.16
pip install -i https://pypi.doubanio.com/simple/ opencv-contrib-python==3.4.2.16
2.常用操作
import pyautogui
pyautogui.PAUSE = 1 # 调用在动作执行后暂停的秒数
pyautogui.FAILSAFE = TRUE # 启动自动防故障功能,将鼠标移动到左上坐标(0,0),抛出failSafeException异常
x, y = 100, 100
print(pyautogui.onScreen(x, y)) # 结果为true
width, height = pyautogui.size() #屏幕的宽度和高度
3.鼠标操作
import pyautogui
currentMouseX, currentMouseY = pyautugui.position() #鼠标当前位置
# 控制鼠标移动,
for i in range(2):
pyautugui.moveTo(100, 100, duration=0.25) # 移动到(100, 100)
pyautugui.moveTo(200, 100, duration=0.25)
pyautugui.moveTo(200, 200, duration=0.25)
pyautugui.moveTo(100, 200, duration=0.25)
for i in range(2):
pyautugui.moveRel(100, 0, duration=0.25) # 从当前位置移动100像素
pyautugui.moveTo(0, 100, duration=0.25)
pyautugui.moveTo(-100, 0, duration=0.25)
pyautugui.moveTo(0, -100, duration=0.25)
# 缓动/渐变函数可以改变光标移动过程的速度和方向。通常鼠标是匀速直线运动,这就是线性缓动/渐变函数。
# 开始很慢,不断加速
pyautogui.moveTo(100, 100, 2, pyautogui.easeInQuad)
# 开始很快,不断减速
pyautogui.moveTo(100, 100, 2, pyautogui.easeOutQuad)
# 开始和结束都快,中间比较慢
pyautogui.moveTo(100, 100, 2, pyautogui.easeInOutQuad)
# 一步一徘徊前进
pyautogui.moveTo(100, 100, 2, pyautogui.easeInBounce)
# 徘徊幅度更大,甚至超过起点和终点
pyautogui.moveTo(100, 100, 2, pyautogui.easeInElastic)
# 鼠标拖拽
pyautogui.dragTo(100, 200, button="left") # 按住鼠标左键拖拽到(100,200)的位置
pyautogui.dragTo(100, 200, 2, button="left") # 按住鼠标左键用2s把鼠标拖拽到(100, 200)的位置
pyautogui.dragRel(0, -60, duration=0.2) # 按住鼠标左键,用0.2秒钟把鼠标向上拖拽
# 鼠标左右键
pyautugui.mouseDown()
pyautogui.mouseUp() # 鼠标左键按下再松开
pyautogui.mouseDown(button="right") # 按下鼠标右键
pyautogui.mouseUp(button="right", x=100, y=100) # 移动到(100,100)位置,松开右键
# 鼠标点击
# num_of_clicks:点击次数
# secs_between_clicks:点击时间间隔
pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks, button='left')
pyautogui.click(10, 20, 2, 0.25, button='left') # 移动到(10,20)点击左键两次
pyautogui.doubleClick() # 鼠标当前位置双击
pyautogui.doubleClick(x=100, y=150, button="left") # 鼠标在(100,150)位置双击
pyautogui.tripleClick() # 鼠标当前位置左击三下
# 鼠标滚动
# scroll函数控制鼠标滚轮的滚动,amount_to_scroll参数表示滚动的格数。正数则页面向上滚动,负数则向下滚动
pyautogui.scroll(clicks=amount_to_scroll, x=moveToX, y=moveToY)
pyautogui.scroll(10, x=100, y=100) # 移动到(100, 100)位置再向上滚动10格
pyautogui.scroll(10) # 向上滚动10格
pyautogui.scroll(-10) # 向下滚动10格
4.键盘操作
import pyautogui
pyautogui.typewrite('Hello world!') # 输入Hello world!字符串
pyautogui.typewrite('Hello world!', interval=0.25) # 每次输入间隔0.25秒,输入Hello world!
pyautogui.press('enter') # 点击回车键
pyautogui.press(['left', 'left', 'left', 'left']) # 按下四次左方向键
pyautogui.keyDown('shift') # 按下'shift'键
pyautogui.keyUp('shift') # 松开'shift'键
pyautogui.hotkey('ctrl', 'v') # 组合按键(Ctrl+V),粘贴功能,按下并松开'ctrl'和'v'按键
pyautogui.KEYBOARD_KEYS = ['\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.',
'/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@',
'[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~',
'accept', 'add', 'alt', 'altleft', 'altright', 'apps', 'backspace', 'browserback',
'browserfavorites', 'browserforward', 'browserhome', 'browserrefresh', 'browsersearch',
'browserstop', 'capslock', 'clear', 'convert', 'ctrl', 'ctrlleft', 'ctrlright', 'decimal',
'del', 'delete', 'divide', 'down', 'end', 'enter', 'esc', 'escape', 'execute', 'f1', 'f10',
'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f2', 'f20', 'f21', 'f22',
'f23', 'f24', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'final', 'fn', 'hanguel', 'hangul',
'hanja', 'help', 'home', 'insert', 'junja', 'kana', 'kanji', 'launchapp1', 'launchapp2',
'launchmail', 'launchmediaselect', 'left', 'modechange', 'multiply', 'nexttrack',
'nonconvert', 'num0', 'num1', 'num2', 'num3', 'num4', 'num5', 'num6', 'num7', 'num8', 'num9',
'numlock', 'pagedown', 'pageup', 'pause', 'pgdn', 'pgup', 'playpause', 'prevtrack', 'print',
'printscreen', 'prntscrn', 'prtsc', 'prtscr', 'return', 'right', 'scrolllock', 'select',
'separator', 'shift', 'shiftleft', 'shiftright', 'sleep', 'space', 'stop', 'subtract', 'tab',
'up', 'volumedown', 'volumemute', 'volumeup', 'win', 'winleft', 'winright', 'yen', 'command',
'option', 'optionleft', 'optionright']
5.图像操作
import pyautogui
image = pyautogui.screenshot()
image.save("test.png") # 截取全屏并保存图片
print(image) # 打印图片属性
pyautogui.screenshot(region=(0, 0, 300, 400)) # 区域截图 region(左,上,宽,高)
# 获得文件图片在现在的屏幕上面的坐标,返回的是一个元组(top, left, width, height)
# 如果截图没找到,pyautogui.locateOnScreen()函数返回None
a = pyautogui.locateOnScreen(r'test.png')
print(a) # 打印结果为Box(left=0, top=0, width=300, height=400)
x, y = pyautogui.center(a) # 获得文件图片在现在的屏幕上面的中心坐标
print(x, y) # 打印结果为150 200
x, y = pyautogui.locateCenterOnScreen(r'region_screenshot.png') # 这步与上面的四行代码作用一样
print(x, y) # 打印结果为150 200
# 匹配屏幕所有与目标图片的对象,可以用for循环和list()输出
pyautogui.locateAllOnScreen(r'C:\Users\ZDH\Desktop\PY\region_screenshot.png')
for pos in pyautogui.locateAllOnScreen(r'C:\Users\ZDH\Desktop\PY\region_screenshot.png'):
print(pos)
# 打印结果为Box(left=0, top=0, width=300, height=400)
a = list(pyautogui.locateAllOnScreen(r'C:\Users\ZDH\Desktop\PY\region_screenshot.png'))
print(a) # 打印结果为[Box(left=0, top=0, width=300, height=400)]
6.应用
def screenshots_and_click(self, folder, filename, _x, _y, width, height, threshold=Settings.THRESHOLD, times=1, timeout=Settings.FIND_TIMEOUT): “””截图并点击截图图片””” folder_file = self.create_folder(path.PLAYER_PATH, folder) # 创建指定位置文件夹 time.sleep(4) pyautogui.moveTo(_x, _y, duration=0.25) if platform.system() == “Darwin”: image = pyautogui.screenshot(region=(_x 2, _y 2, width 2, height 2)) image.save(os.path.join(folder_file, filename)) # 截图并指定位置保存 logger.info(“Picture {} saved successfully!”.format(filename)) else: image = pyautogui.screenshot(region=(_x, _y, width, height)) image.save(os.path.join(folder_file, filename)) logger.info(“Picture {} saved successfully!”.format(filename)) start_time = time.time() if time.time() - start_time > timeout: raise TargetNotFoundError(“Picture is not Found!”) else: _pos = pyautogui.locateCenterOnScreen(os.path.join(folder_file, filename), confidence=threshold) # 获取截图图片中心坐标 if platform.system() == ‘Darwin’: pos = (_pos[0] / 2, _pos[1] / 2) self.click_mouse_coordinate(pos) # 移动并点击图片坐标 else: self.click_mouse_coordinate(_pos) logger.info(“click picture {}”.format(filename)) ```