Python + ADB 手机自动化控制教程
教程简介
本教程将教你使用 Python 和 ADB 工具实现 PC 控制 Android 手机自动滑动视频的功能。适合零基础开发者,所有步骤可直接跟随操作。
一、环境准备
1.1 系统要求
- Windows 10/11、macOS 或 Linux
- Android 手机(需开启开发者模式)
- USB 数据线
1.2 安装 Python
检查是否已安装:
python --version
如果显示版本号(如 Python 3.x.x),则已安装,跳到 1.3。
Windows 安装:
- 访问 https://www.python.org/downloads/
- 下载 Python 3.8 或更高版本
- 安装时勾选 “Add Python to PATH”
- 打开命令提示符(cmd),输入
python --version验证
macOS 安装:
# 使用 Homebrew
brew install python3
Linux 安装:
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip# CentOS/RHEL
sudo yum install python3 python3-pip
1.3 安装 ADB 工具
方法一:安装完整 Android SDK Platform-Tools(推荐)
- 访问 https://developer.android.com/tools/releases/platform-tools
- 下载对应系统版本
- 解压到任意目录(如
C:\platform-tools) - 添加到系统环境变量 PATH
Windows 添加环境变量:
- 右键"此电脑" → “属性” → “高级系统设置”
- “环境变量” → 找到 Path → “编辑” → “新建”
- 添加 ADB 工具路径(如
C:\platform-tools)
macOS/Linux 添加环境变量:
# 编辑 ~/.bashrc 或 ~/.zshrc
echo 'export PATH=$PATH:/path/to/platform-tools' >> ~/.zshrc
source ~/.zshrc
验证安装:
adb version
应显示类似:Android Debug Bridge version 1.0.41
1.4 手机设置
开启开发者模式:
- 设置 → 关于手机
- 连续点击"版本号"7次
- 返回设置 → 系统 → 开发者选项
- 开启"USB调试"
- 用 USB 线连接手机到电脑
- 手机上弹出授权提示,点击"允许"
验证连接:
adb devices
应显示类似:
List of devices attached
ABC123456789 device
如果显示 unauthorized,检查手机授权提示。
二、安装 Python 依赖
2.1 安装 pure-python-adb
打开终端/命令提示符,执行:
pip install pure-python-adb
可能遇到的问题:
如果提示 pip: command not found:
# 尝试使用 pip3
pip3 install pure-python-adb# 或者使用 python -m pip
python -m pip install pure-python-adb
如果安装速度慢,使用国内镜像:
pip install pure-python-adb -i https://pypi.tuna.tsinghua.edu.cn/simple
2.2 验证安装
python -c "from ppadb.client import Client; print('安装成功')"
如果没有报错且显示"安装成功",则安装完成。
三、编写自动化脚本
3.1 创建项目目录
# 创建项目文件夹
mkdir phone-automation
cd phone-automation
3.2 测试连接脚本
创建 test_connection.py:
"""
测试手机连接脚本
功能:验证 ADB 连接是否正常
"""from ppadb.client import Clientdef test_connection():try:# 连接 ADB 服务器adb = Client(host="127.0.0.1", port=5037)# 获取设备列表devices = adb.devices()if len(devices) == 0:print("❌ 未检测到设备")print("请检查:")print("1. 手机是否通过 USB 连接")print("2. 是否开启 USB 调试")print("3. 是否授权此电脑")return Falseprint(f"✅ 检测到 {len(devices)} 个设备")for device in devices:print(f"设备序列号: {device.serial}")return Trueexcept Exception as e:print(f"❌ 连接失败: {e}")print("请确保 ADB 服务已启动,执行: adb start-server")return Falseif __name__ == "__main__":test_connection()
运行测试:
python test_connection.py
3.3 基础滑动脚本
创建 basic_swipe.py:
"""
基础滑动脚本
功能:每隔指定时间执行一次向上滑动
"""from ppadb.client import Client
import timedef swipe_up(device):"""执行向上滑动操作参数说明:input swipe x1 y1 x2 y2 durationx1, y1: 起始坐标x2, y2: 结束坐标duration: 滑动持续时间(毫秒)常见分辨率的滑动坐标:- 1080x2400: swipe 500 1800 500 600 300- 1080x1920: swipe 500 1500 500 500 300- 720x1280: swipe 360 1000 360 400 300"""# 这里使用通用坐标,适配大多数手机# 从屏幕下方(80%)滑到上方(20%)device.shell("input swipe 500 1500 500 500 300")print("✅ 执行滑动操作")def main():try:# 连接设备adb = Client(host="127.0.0.1", port=5037)devices = adb.devices()if len(devices) == 0:print("❌ 未检测到设备,请先连接手机")return# 使用第一个设备device = devices[0]print(f"📱 已连接设备: {device.serial}")# 配置参数interval = 5 # 滑动间隔(秒)count = 0 # 滑动计数print(f"⏰ 每 {interval} 秒滑动一次")print("按 Ctrl+C 停止\n")# 持续滑动while True:count += 1print(f"[{count}] {time.strftime('%H:%M:%S')} ", end="")swipe_up(device)time.sleep(interval)except KeyboardInterrupt:print(f"\n\n⏹️ 已停止,共执行 {count} 次滑动")except Exception as e:print(f"\n❌ 发生错误: {e}")if __name__ == "__main__":main()
运行脚本:
python basic_swipe.py
3.4 完整功能脚本
创建 auto_swipe.py:
"""
完整自动化滑动脚本
功能:
1. 支持自定义滑动间隔和次数
2. 支持指定应用包名(可选启动应用)
3. 记录滑动日志
4. 异常处理和重连机制
"""from ppadb.client import Client
import time
import argparse
from datetime import datetimeclass PhoneAutomation:def __init__(self, interval=5, total_count=None, app_package=None):"""初始化自动化控制器参数:interval: 滑动间隔(秒)total_count: 总滑动次数(None=无限次)app_package: 应用包名(可选)"""self.interval = intervalself.total_count = total_countself.app_package = app_packageself.device = Noneself.count = 0def connect_device(self):"""连接设备"""try:adb = Client(host="127.0.0.1", port=5037)devices = adb.devices()if len(devices) == 0:print("❌ 未检测到设备")return Falseself.device = devices[0]print(f"✅ 已连接设备: {self.device.serial}")return Trueexcept Exception as e:print(f"❌ 连接失败: {e}")return Falsedef start_app(self):"""启动指定应用(如果配置了包名)"""if not self.app_package:returntry:# 启动应用self.device.shell(f"monkey -p {self.app_package} -c android.intent.category.LAUNCHER 1")print(f"📱 已启动应用: {self.app_package}")time.sleep(2) # 等待应用启动except Exception as e:print(f"⚠️ 启动应用失败: {e}")def swipe_up(self):"""执行向上滑动"""try:self.device.shell("input swipe 500 1500 500 500 300")self.count += 1current_time = datetime.now().strftime('%H:%M:%S')print(f"[{self.count}] {current_time} ✅ 滑动成功")return Trueexcept Exception as e:print(f"❌ 滑动失败: {e}")return Falsedef should_continue(self):"""判断是否继续执行"""if self.total_count is None:return Truereturn self.count < self.total_countdef run(self):"""运行自动化任务"""if not self.connect_device():returnself.start_app()print(f"\n⏰ 滑动间隔: {self.interval} 秒")if self.total_count:print(f"🎯 目标次数: {self.total_count} 次")else:print(f"🔄 持续运行(按 Ctrl+C 停止)")print("-" * 50)try:while self.should_continue():if not self.swipe_up():# 滑动失败,尝试重连print("🔄 尝试重新连接...")if not self.connect_device():breakif self.should_continue():time.sleep(self.interval)except KeyboardInterrupt:print("\n\n⏹️ 用户停止")finally:print(f"\n📊 统计信息:")print(f" - 总滑动次数: {self.count}")print(f" - 运行时间: {self.count * self.interval} 秒")def main():# 命令行参数解析parser = argparse.ArgumentParser(description='手机自动化滑动脚本')parser.add_argument('-i', '--interval', type=int, default=5, help='滑动间隔(秒),默认5秒')parser.add_argument('-n', '--count', type=int, default=None,help='滑动次数,不指定则无限循环')parser.add_argument('-p', '--package', type=str, default=None,help='应用包名,如:com.ss.android.ugc.aweme(抖音)')args = parser.parse_args()# 创建并运行自动化任务automation = PhoneAutomation(interval=args.interval,total_count=args.count,app_package=args.package)automation.run()if __name__ == "__main__":main()
四、运行指南
4.1 基础运行
默认配置运行(5秒间隔,无限循环):
python auto_swipe.py
4.2 自定义参数运行
设置间隔为10秒:
python auto_swipe.py -i 10
设置滑动20次后自动停止:
python auto_swipe.py -n 20
启动抖音并自动滑动:
python auto_swipe.py -p com.ss.android.ugc.aweme
组合参数(每8秒滑动一次,共50次,启动抖音):
python auto_swipe.py -i 8 -n 50 -p com.ss.android.ugc.aweme
4.3 查看帮助
python auto_swipe.py -h
4.4 停止脚本
运行中按 Ctrl + C 即可停止。
五、常见应用包名
抖音:com.ss.android.ugc.aweme
快手:com.smile.gifmaker
B站:tv.danmaku.bili
微信:com.tencent.mm
QQ:com.tencent.mobileqq
微博:com.sina.weibo
查找应用包名方法:
# 先打开目标应用,然后执行:
adb shell dumpsys window | grep mCurrentFocus
六、调整滑动坐标
如果滑动效果不理想,需要根据手机分辨率调整坐标。
查看手机分辨率:
adb shell wm size
根据分辨率调整:
假设分辨率为 1080x2400:
# 计算公式:
# x坐标 = 屏幕宽度 / 2 = 1080 / 2 = 540
# y1坐标(起点)= 屏幕高度 * 0.8 = 2400 * 0.8 = 1920
# y2坐标(终点)= 屏幕高度 * 0.2 = 2400 * 0.2 = 480# 修改 swipe_up 函数中的命令为:
device.shell("input swipe 540 1920 540 480 300")
七、故障排查
7.1 “未检测到设备”
解决方案:
# 1. 检查设备连接
adb devices# 2. 重启 ADB 服务
adb kill-server
adb start-server# 3. 检查驱动(Windows)
# 在设备管理器中查看是否有黄色感叹号# 4. 重新授权
# 拔掉 USB 线重新插入,手机上重新授权
7.2 “ModuleNotFoundError: No module named ‘ppadb’”
解决方案:
# 确认 Python 环境
python --version# 重新安装
pip uninstall pure-python-adb
pip install pure-python-adb
7.3 滑动无反应
解决方案:
- 确认应用已在前台运行
- 调整滑动坐标(参考第六节)
- 增加滑动时间:
300改为500 - 检查手机是否锁屏
7.4 脚本运行卡住
解决方案:
# 检查 ADB 进程
ps aux | grep adb# 杀掉所有 ADB 进程
killall adb# 重启 ADB
adb start-server
八、进阶功能
8.1 添加随机间隔
让滑动更像人类操作:
import random# 在 auto_swipe.py 的 run 方法中修改:
time.sleep(self.interval + random.uniform(-1, 1))
8.2 添加日志文件
import logging# 在脚本开头添加:
logging.basicConfig(filename='swipe_log.txt',level=logging.INFO,format='%(asctime)s - %(message)s'
)# 在 swipe_up 方法中添加:
logging.info(f"滑动第 {self.count} 次")
8.3 多设备控制
# 修改 connect_device 方法,支持选择设备:
devices = adb.devices()
for i, device in enumerate(devices):print(f"{i}: {device.serial}")
choice = int(input("选择设备序号: "))
self.device = devices[choice]
九、完整项目结构
phone-automation/
├── test_connection.py # 测试连接脚本
├── basic_swipe.py # 基础滑动脚本
├── auto_swipe.py # 完整功能脚本
└── swipe_log.txt # 日志文件(运行后生成)
十、总结
恭喜你完成教程!现在你已经掌握:
✅ Python + ADB 环境搭建
✅ 手机连接和授权
✅ 基础自动化脚本编写
✅ 完整功能脚本开发
✅ 参数化配置和异常处理
下一步建议:
- 学习更多 ADB 命令(点击、长按、输入文本等)
- 探索 uiautomator2 进行元素定位
- 研究图像识别技术实现更智能的自动化
参考资源:
- ADB 官方文档:https://developer.android.com/tools/adb
- pure-python-adb GitHub:https://github.com/Swind/pure-python-adb
