之前使用pymouse做过简单的模拟,现在需要录制很多个坐标,并且位置也没有统一的标准,所以写一个代码把位置全部进行录制,本文主要介绍录制部分,一些基础的使用可以看这篇博客的代码:
(16条消息) python模拟鼠标和键盘_python模拟鼠标键盘操作_vener_的博客-优快云博客
No module named 'windows' 找不到可以看这个解决方法
ModuleNotFoundError: No module named ‘windows‘_modulenotfounderror: no module named 'windows-优快云博客
不用按照这个里边安装pyhook,看下边这个就行
由于python的版本不同,导致windows.py的源码也不同,所以这里附上两个版本的代码,但是每个版本安装的时候都需要把windows.py中的pyhook改成pyWinhook
详见python3.8及以上版本安装pyHook失败的解决方案_pyhook安装失败-优快云博客
1.python3.9
这个版本的实现比较简单,而且当时也没有想太多,所以直接把类的实例化放到循环里了,不太好,后来低版本出现问题才改掉,这个版本也懒得改了
import time
import pymouse
from pymouse import PyMouseEvent
log = list()#最终的记录变量
class ClickRecorder(PyMouseEvent):
def __init__(self,num):
self.num = num
PyMouseEvent.__init__(self)
def click(self, x, y, button, press):
if button == 1 and press:
print("左键单击事件发生!")
print("鼠标位置:({}, {})".format(x, y))
log.append((x,y))
if(len(log)==self.num):
print('{}个位置已经记录'.format(self.num))
self.stop()
def loc_log(file,num):#记录鼠标单击的位置
log.clear()
print('存储文件:',file,'记录数量:',num)
click_recorder = ClickRecorder(num)
click_recorder.run()
# 写入txt文件
with open(file, 'w') as file:
for item in log:
line = ' '.join(str(x) for x in item) + '\n'
file.write(line)
if __name__ == '__main__':
m = pymouse.PyMouse() # 鼠标的实例
#files里的文件名称比较机密我就直接删掉了,变量都是字符串
files = [file6,file0,file1,file2,file30,file31,file32,file4,file5,file8,file9,file7]
nums = [1,3,1,1,12,15,6,1,1,1,1,1]
print('单机左键表示选中位置!!!')
for i in range(len(files)):
time.sleep(1)
print('5秒钟后开始记录'+files[i]+',请做好准备!!!')
for j in range(5):
print(5-j)
time.sleep(1)
loc_log(files[i]+'.txt',nums[i])
2.python3.6
首先的不同是安装pyWinhook的版本,好像是需要特定的pyWinhook版本,否则会出现DL Load Failed错误,具体什么版本可以搜索以下,有些忘了
使用上述代码会出现在循环中实例化类的时候num的值不更新,原因是因为这个版本的windows.py中没有stop函数,于是将代码改成如下,并修改了以下windows.py的源码,在run函数中通过判断self.isrunning的值结束循环即可
import time
import pymouse
from pymouse import PyMouseEvent
log = list()#最终的记录变量
global num
class ClickRecorder(PyMouseEvent):
def __init__(self):
PyMouseEvent.__init__(self)
self.is_running = True
def click(self, x, y, button, press):
global num
if button == 1 and press:
print("左键单击事件发生!")
print("鼠标位置:({}, {})".format(x, y))
log.append((x,y))
print(len(log),num)
if(len(log)>=num):
print('{}个位置已经记录'.format(len(log)))
self.is_running = False
def loc_log(file,click_recorder,n):#记录鼠标单击的位置
log.clear()
global num
num = n
print('存储文件:',file,'记录数量:',n)
click_recorder.is_running = True
click_recorder.run()
# 写入txt文件
with open(file, 'w') as file:
for item in log:
line = ' '.join(str(x) for x in item) + '\n'
file.write(line)
if __name__ == '__main__':
m = pymouse.PyMouse() # 鼠标的实例
#files同上
files = [file6,file0,file1,file2,file30,file31,file32,file4,file5,file8,file9,file7]
nums = [1,3,1,1,12,15,6,1,1,1,1,1]
print('单机左键表示选中位置!!!第一次点击好像会卡顿')
click_recorder = ClickRecorder()
for i in range(len(files)):
time.sleep(1)
print('5秒钟后开始记录'+files[i]+',请做好准备!!!')
for j in range(5):
print(5-j)
time.sleep(1)
loc_log(files[i]+'.txt',click_recorder,nums[i])
还有一个要注意的点就是,类的实例化要写在循环的外边