import subprocess import os import time def screenshot_basic(save_path="screenshot.png"): """ 基础截图功能:先保存到手机,再拉取到电脑 Args: save_path: 保存到电脑的路径 """ try: # 1. 在手机上进行截图并保存到/sdcard/目录 print("正在截图...") subprocess.run( ["adb", "shell", "screencap", "-p", "/sdcard/temp_screen.png"], check=True, # check=True会在命令失败时抛出异常[citation:2] timeout=10 ) # 2. 将截图从手机拉取到电脑 print("正在传输截图...") subprocess.run( ["adb", "pull", "/sdcard/temp_screen.png", save_path], check=True, timeout=10 ) # 3. 清理手机上的临时文件 subprocess.run( ["adb", "shell", "rm", "/sdcard/temp_screen.png"], check=True, timeout=5 ) print(f"截图已保存到: {save_path}") return True except subprocess.CalledProcessError as e: print(f"ADB命令执行失败: {e}") return False except subprocess.TimeoutExpired as e: print(f"命令执行超时: {e}") return False except FileNotFoundError: print("未找到ADB命令,请确认ADB已安装并配置环境变量") return False def tap(x, y, device_serial=None): """ 在指定坐标位置执行点击操作 Args: x: X坐标 y: Y坐标 device_serial: 设备序列号(可选,多设备时需要指定) Returns: bool: 是否成功 """ try: cmd = ["adb"] if device_serial: cmd.extend(["-s", device_serial]) cmd.extend(["shell", "input", "tap", str(x), str(y)]) result = subprocess.run(cmd, capture_output=True, text=True, timeout=5) return result.returncode == 0 except Exception as e: print(f"点击失败: {e}") return False def swipe_vertical(x, y1, y2, duration=300, device_serial=None): """ 在指定X坐标位置,从y1垂直滑动到y2 Args: x: X轴坐标 y1: 起始Y坐标 y2: 结束Y坐标 duration: 滑动持续时间(毫秒),默认300ms device_serial: 设备序列号(可选,多设备时需要指定) Returns: bool: 是否成功 """ try: # 构建ADB命令 cmd = ["adb"] if device_serial: cmd.extend(["-s", device_serial]) cmd.extend([ "shell", "input", "swipe", str(x), str(y1), str(x), str(y2), str(duration) ]) print(f"滑动: ({x}, {y1}) -> ({x}, {y2}) 持续时间: {duration}ms") # 执行滑动 result = subprocess.run(cmd, capture_output=True, text=True, timeout=5) if result.returncode == 0: print("滑动成功") return True else: print(f"滑动失败: {result.stderr}") return False except Exception as e: print(f"执行滑动时出错: {e}") return False # 使用示例 if __name__ == "__main__": # 先确认设备已连接 result = subprocess.run(["adb", "devices"], capture_output=True, text=True) print("当前连接的设备:") print(result.stdout) while True: swipe_vertical(100*2, 600*2, 300*2) time.sleep(0.5) swipe_vertical(100*2, 600*2, 300*2) time.sleep(0.5) tap(416 * 2, 790 * 2) time.sleep(1) tap(269 * 2, 875 * 2) time.sleep(1) # tap(103 * 4, 262 * 4) # time.sleep(num1) # swipe_vertical(138*4, 446*4, 578*4) # time.sleep(5) # time.sleep(2) screenshot_basic("my_screenshot.png")