运行环境 : python 3.6.0

1. 安装第三方库 pyautogui

1) 官方库

pip install pyautogui

2) 或者从清华镜像或者从其他镜像安装

pip -i https://pypi.tuna.tsinghua.edu.cn/simple install pyautogui

 2. 编写执行程序

# -*- encoding: utf-8 -*-

import time
import pyautogui as pag

try:
    while True:
        print("Press Ctrl-C to end")
        screenWidth, screenHeight = pag.size()  # 获取屏幕的尺寸
        x, y = pag.position()  # 返回鼠标的坐标
        print("Screen size: (%s %s),  Position : (%s, %s)\n" % (screenWidth, screenHeight, x, y))  # 打印坐标

        time.sleep(1)  # 每个1s中打印一次 , 并执行清屏
        os.system('cls')  # 执行系统清屏指令
except KeyboardInterrupt:
    print('end')

运行结果如图 :

python 模拟鼠标移动 python移动鼠标位置_鼠标位置

3. pyautogui 其他常用函数

moveTo(x, y)  # 将鼠标移动到指定的 x y 坐标 .

moveRel(xOffset, yOffset)  # 相对于当前位置移动鼠标 .

dragTo(x, y)  # 按下左键移动鼠标 .

dragRel(xOffset, yOffset)  # 按下左键 , 相对于当前位置移动鼠标 .

click(x, y, button)  # 模拟点击 (默认是左键) .

rightClick()  # 模拟右键点击。

middleClick()  # 模拟中键点击。

doubleClick()  # 模拟左键双击。

mouseDown(x, y, button)  # 模拟在 x、y 处按下指定鼠标按键。

mouseUp(x, y, button)  # 模拟在 x、y 处释放指定键。

scroll(units)  # 模拟滚动滚轮。正参数表示向上滚动, 负参数表示向下滚动。

typewrite(message)  # 键入给定消息字符串中的字符。

typewrite([key1, key2, key3])  # 键入给定键字符串。

press(key)  # 按下并释放给定键。

keyDown(key)  # 模拟按下给定键。

keyUp(key)  # 模拟释放给定键。

hotkey([key1, key2, key3])  # 模拟按顺序按下给定键字符串, 然后以相反的顺序释放。

screenshot()  # 返回屏幕快照的 Image 对象