使用前需安装以下两个库:

1
2
pip install pyautogui
pip install pillow

主要代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

import pyautogui
import time


# 获取鼠标位置
def get_mouse_position():
time.sleep(5) # 准备时间
print('开始获取鼠标位置')
try:
for i in range(10):
# Get and print the mouse coordinates.
x, y = pyautogui.position()
positionStr = '鼠标坐标点(X,Y)为:{},{}'.format(str(x).rjust(4), str(y).rjust(4))
pix = pyautogui.screenshot().getpixel((x, y)) # 获取鼠标所在屏幕点的RGB颜色
positionStr += ' RGB:(' + str(pix[0]).rjust(3) + ',' + str(pix[1]).rjust(3) + ',' + str(pix[2]).rjust(
3) + ') '
print(positionStr)
time.sleep(0.5) # 停顿时间
except:
print('获取鼠标位置失败')


if __name__ == "__main__":
get_mouse_position()
input("\n按Enter键退出...")

这个脚本其实属于一个辅助脚本。那么有什么用呢?知道了光标位置,我们可以写脚本移动光标模拟点击。而且,我比较喜欢的一个功能是它可以把光标位置所在像素点的RGB颜色读出来,好处就是方便定位判定点。通俗来讲就是如果哪个点或哪几个点变成啥颜色了则执行啥操作。
比如刚整的一个自动刷某安全教育视频脚本中的一段:

1
2
3
4
5
6
7
while 1:
time.sleep(3)
matchColor1 = pyautogui.pixelMatchesColor(1303, 976, (255, 255, 255), tolerance=0)
matchColor2 = pyautogui.pixelMatchesColor(787, 976, (255, 255, 255), tolerance=0)
matchColor3 = pyautogui.pixelMatchesColor(286, 976, (255, 255, 255), tolerance=0)
if matchColor1 and matchColor2 and matchColor3:
# ......

作用是判断白色进度条是不是满了,满了的话执行if里的操作。
比如可以点下一个视频:

1
2
pyautogui.moveTo(x, y, duration=0.25)
pyautogui.click()

当然具体操作过程还有很多细节,这里不细嗦。