跳到主要内容
极客日志极客日志
首页博客AI提示词GitHub精选代理工具
搜索
|注册
博客列表
Python大前端

Python 移动端 UI 自动化脚本开发实战

使用 Python 和 uiautomator2 库进行移动端 UI 自动化的基础配置与核心代码实现。内容包括环境搭建(ADB、Python 依赖)、设备连接配置以及自动化脚本的基本结构,旨在帮助开发者理解如何通过代码控制移动应用界面。

漫步发布于 2026/3/15更新于 2026/4/2613 浏览
Python 移动端 UI 自动化脚本开发实战

前言

本教程将介绍如何使用 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)
        
        .setup_logging()
        
        .connect_device(device_serial)
        
        .stats = {
            : ,
            : ,
            : ,
            : ,
            : datetime.datetime.now()
        }
        logger.info()
        logger.info()
        logger.info()

     ():
        
        default_config = {
            : {
                : {: , : },
                : {: , : },
                : {: , : },
                : {: , : },
                : {: , : }
            },
            : {
                : ,
                : ,
                : ,
                : 
            },
            : {
                : ,
                : ,
                : ,
                : 
            },
            : {
                : ,
                : ,
                : 
            }
        }
        :
             os.path.exists(config_file):
                 (config_file, , encoding=)  f:
                    user_config = json.load(f)
                default_config.update(user_config)
                logger.info()
         Exception  e:
            logger.warning()
         default_config

     ():
        
        log_dir = 
          os.path.exists(log_dir):
            os.makedirs(log_dir)
        log_file = 
        logger.add(log_file, rotation=, retention=, =)
        logger.add(sys.stderr, =)

     ():
        
        :
             device_serial:
                .d = u2.connect(device_serial)
            :
                .d = u2.connect()
            .device_info = {
                : .d.info.get(, ),
                : ... 
            }
         Exception  e:
            logger.error()
# 设置日志
self
# 连接设备
self
# 运行统计
self
'total_cycles'
0
'successful_cycles'
0
'total_earnings'
0
'total_runtime'
0
'start_time'
"🎯 移动端自动化机器人初始化完成"
f"📱 设备:{self.device_info}"
f"⚙️ 配置:{json.dumps(self.config, indent=2, ensure_ascii=False)}"
def
load_config
self, config_file
"""加载配置文件"""
'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
with
open
'r'
'utf-8'
as
f"📄 已加载配置文件:{config_file}"
except
as
f"配置文件加载失败,使用默认配置:{e}"
return
def
setup_logging
self
"""设置日志系统"""
"logs"
if
not
f"{log_dir}/music_auto_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
"500 MB"
"10 days"
format
"{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}"
format
"{time:HH:mm:ss} | {level} | {message}"
def
connect_device
self, device_serial
"""连接设备"""
try
if
self
else
self
self
'model'
self
'productName'
'Unknown'
'reso'
# 代码在输入中截断
except
as
f"设备连接失败:{e}"

目录

  1. 前言
  2. 第一章:环境准备与基础配置
  3. 1.1 硬件要求
  4. 1.2 软件安装
  5. 1. 安装 ADB 工具
  6. Windows: 下载 Android SDK Platform-Tools
  7. Mac: brew install android-platform-tools
  8. Linux: sudo apt install adb
  9. 2. 安装 Python 依赖
  10. 3. 初始化设备连接
  11. 1.3 手机设置
  12. 第二章:核心脚本完整代码
  • 💰 8折买阿里云服务器限时8折了解详情
  • 💰 8折买阿里云服务器限时8折购买
  • 🦞 5分钟部署阿里云小龙虾了解详情
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • FastGithub 部署指南:智能 DNS 解析优化 GitHub 访问
  • DICOM 标准详解:文件解析、Java/Python 库与 AI 应用
  • Spring Bean 管理与 Spring Boot 自动配置原理
  • Python GUI 可视化设计工具 tkinter-helper 介绍
  • 银行个人贷款违约风险预测:基于逻辑回归模型
  • Java 对象比较详解:==、equals 与排序策略
  • 昇腾 NPU 部署 Llama 2 模型的性能测试与优化实践
  • 知网与维普 AIGC 检测机制对比及选择建议
  • 2026年全球AI大模型深度研究报告
  • System Verilog 教程:从基础到高级验证
  • Flutter 集成 DeepSeek API 实现鸿蒙端 AI 对话与流式渲染
  • AI 编程工具选型:Copilot、Cursor、Codex 核心差异
  • 大语言模型(LLM)初学者入门教程与学习路线指南
  • 多种智能优化算法改进在线顺序极限学习机 (OSELM) 预测模型
  • AI 与 SQL 双驱动 ER 图在线生成工具
  • LeetCode 383. 赎金信:哈希表与数组计数法对比
  • Verilog 组合逻辑电路设计:从原理到 FPGA 实战
  • AI 生成论文参考文献存在幻觉风险,如何确保引用真实可靠?
  • JDK 27 引入后量子混合密钥交换,应对量子计算威胁
  • 大语言模型 LLM 解决 AI 幻觉方法深度分析

相关免费在线工具

  • curl 转代码

    解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online

  • JSON 压缩

    通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online