前言
本教程将介绍如何使用 Python 进行移动端 UI 自动化测试,通过代码控制应用界面,实现重复性任务的自动化处理。
第一章:环境准备与基础配置
1.1 硬件要求
- Android 手机一部(建议使用备用机)
- USB 数据线
- 电脑(Windows/Mac/Linux 均可)
1.2 软件安装
# 1. 安装 ADB 工具
# Windows: 下载 Android SDK Platform-Tools
# Mac: brew install android-platform-tools
# Linux: sudo apt install adb
# 2. 安装 Python 依赖
pip install uiautomator2
pip install loguru # 更好的日志记录
# 3. 初始化设备连接
python -m uiautomator2 init
1.3 手机设置
- 开启开发者选项(连续点击'关于手机'中的版本号)
- 开启 USB 调试
- 设置屏幕常亮(15 分钟以上)
- 关闭锁屏密码
第二章:核心脚本完整代码
"""
移动端 UI 自动化脚本 v2.0
功能:模拟用户操作,执行界面交互
特点:精准坐标控制、错误重试、完整日志
"""
import uiautomator2 as u2
import time
import datetime
import random
import logging
from loguru import logger
import json
import os
import sys
class MusicAdAutoFarmer:
"""移动端 UI 自动化核心类"""
def __init__(self, device_serial=None, config_file="config.json"):
"""初始化自动化机器人
Args:
device_serial: 设备序列号,None 为自动连接
config_file: 配置文件路径
"""
# 加载配置
self.config = self.load_config(config_file)
# 设置日志
self.setup_logging()
# 连接设备
self.connect_device(device_serial)
# 运行统计
self.stats = {
'total_cycles': 0,
'successful_cycles': 0,
'total_earnings': 0,
'total_runtime': 0,
'start_time': datetime.datetime.now()
}
logger.info("🎯 移动端自动化机器人初始化完成")
logger.info(f"📱 设备:{self.device_info}")
logger.info(f"⚙️ 配置:{json.dumps(self.config, indent=2, ensure_ascii=False)}")
def load_config(self, config_file):
"""加载配置文件"""
default_config = {
'coordinates': {
'swipe_start': {'x': 367, 'y': 1793},
'swipe_end': {'x': 334, 'y': 707},
'go_task_button': {'x': 930, 'y': 633},
'close_ad_button': {'x': 998, 'y': 130},
'happy_receive_button': {'x': 570, 'y': 1321}
},
'timing': {
'ad_watch_time': 480,
'swipe_interval': 35,
'cycle_interval': 300,
'click_wait': 1.5
},
'behavior': {
'swipe_times': 2,
'max_retries': 3,
'random_offset': 5,
'human_like_delay': True
},
'runtime': {
'max_cycles': None,
'auto_restart': True,
'save_screenshots': False
}
}
try:
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
user_config = json.load(f)
default_config.update(user_config)
logger.info(f"📄 已加载配置文件:{config_file}")
except Exception as e:
logger.warning(f"配置文件加载失败,使用默认配置:{e}")
return default_config
def setup_logging(self):
"""设置日志系统"""
log_dir = "logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = f"{log_dir}/music_auto_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logger.add(log_file, rotation="500 MB", retention="10 days", format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}")
logger.add(sys.stderr, format="{time:HH:mm:ss} | {level} | {message}")
def connect_device(self, device_serial):
"""连接设备"""
try:
if device_serial:
self.d = u2.connect(device_serial)
else:
self.d = u2.connect()
self.device_info = {
'model': self.d.info.get('productName', 'Unknown'),
'reso': ... # 代码在输入中截断
}
except Exception as e:
logger.error(f"设备连接失败:{e}")


