最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python?+?uiautomator2手機自動化控制超詳細教程

 更新時間:2026年03月27日 09:41:08   作者:黃思搏  
在移動應(yīng)用開發(fā)領(lǐng)域,APP自動化測試至關(guān)重要,這篇文章主要介紹了Python+uiautomator2手機自動化控制的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

簡介

uiautomator2 是比 ADB 更強大的 Android 自動化框架,支持元素定位、控件操作、應(yīng)用管理等高級功能。本教程適合需要更精細控制的開發(fā)者。

一、環(huán)境準備

1.1 前置要求

  • Python 3.6 或更高版本
  • Android 手機(需開啟開發(fā)者模式和 USB 調(diào)試)
  • USB 數(shù)據(jù)線
  • 已安裝 ADB 工具(參考第一篇教程)

1.2 檢查 Python 環(huán)境

python --version
# 應(yīng)顯示 Python 3.6 或更高版本

1.3 檢查 ADB 連接

adb devices
# 應(yīng)顯示已連接的設(shè)備

二、安裝 uiautomator2

2.1 安裝 Python 庫

pip install uiautomator2

使用國內(nèi)鏡像加速:

pip install uiautomator2 -i https://pypi.tuna.tsinghua.edu.cn/simple

2.2 初始化手機環(huán)境

重要步驟: 首次使用需要在手機上安裝 ATX-Agent 和 uiautomator 服務(wù)。

# 方法一:使用命令行工具初始化
python -m uiautomator2 init
# 方法二:使用 Python 腳本初始化
python
>>> import uiautomator2 as u2
>>> u2.connect_usb()  # 會自動安裝必要組件
>>> exit()

初始化過程:

  1. 會在手機上安裝兩個 APK:
    • ATXAgent.apk - 核心服務(wù)
    • app-uiautomator.apkapp-uiautomator-test.apk - UI 自動化服務(wù)
  2. 安裝過程需要 1-3 分鐘
  3. 手機上會彈出安裝提示,點擊"安裝"

2.3 驗證安裝

創(chuàng)建測試文件 test_u2.py

import uiautomator2 as u2
# 連接設(shè)備
d = u2.connect()  # 自動連接 USB 設(shè)備
print("設(shè)備信息:", d.info)
print("? uiautomator2 安裝成功!")

運行測試:

python test_u2.py

成功會顯示設(shè)備信息(型號、分辨率、Android 版本等)。

三、uiautomator2 核心功能

3.1 設(shè)備連接方式

import uiautomator2 as u2
# 方式1:自動連接(推薦)
d = u2.connect()
# 方式2:通過 USB 連接
d = u2.connect_usb()
# 方式3:通過設(shè)備序列號連接
d = u2.connect('device_serial')
# 方式4:通過 WiFi 連接(需先配置)
d = u2.connect('192.168.1.100')

3.2 基礎(chǔ)操作

# 獲取設(shè)備信息
print(d.info)
# 獲取屏幕分辨率
width, height = d.window_size()
print(f"分辨率: {width}x{height}")
# 截圖
d.screenshot("screen.png")
# 點擊坐標
d.click(500, 1000)
# 滑動
d.swipe(500, 1500, 500, 500, 0.3)  # 從下往上滑
# 長按
d.long_click(500, 1000)
# 輸入文本
d.send_keys("Hello World")
# 按鍵操作
d.press("home")  # 返回主屏幕
d.press("back")  # 返回鍵

3.3 應(yīng)用管理

# 啟動應(yīng)用
d.app_start("com.ss.android.ugc.aweme")
# 停止應(yīng)用
d.app_stop("com.ss.android.ugc.aweme")
# 清除應(yīng)用數(shù)據(jù)
d.app_clear("com.ss.android.ugc.aweme")
# 檢查應(yīng)用是否運行
if d.app_current().get('package') == "com.ss.android.ugc.aweme":
    print("抖音正在運行")
# 獲取當前應(yīng)用信息
current = d.app_current()
print(f"當前應(yīng)用: {current['package']}")

四、編寫自動化腳本

4.1 基礎(chǔ)滑動腳本

創(chuàng)建 u2_basic_swipe.py

"""
uiautomator2 基礎(chǔ)滑動腳本
功能:自動滑動視頻
"""
import uiautomator2 as u2
import time
def main():
    # 連接設(shè)備
    d = u2.connect()
    print(f"? 已連接設(shè)備: {d.info['productName']}")
    # 獲取屏幕尺寸
    width, height = d.window_size()
    print(f"?? 屏幕分辨率: {width}x{height}")
    # 配置參數(shù)
    interval = 5  # 滑動間隔(秒)
    count = 0
    print(f"? 每 {interval} 秒滑動一次")
    print("按 Ctrl+C 停止\n")
    try:
        while True:
            count += 1
            # 從屏幕下方滑到上方
            # 使用相對坐標,自適應(yīng)不同分辨率
            d.swipe(
                width // 2,      # x: 屏幕中央
                height * 0.8,    # y1: 屏幕 80% 位置
                width // 2,      # x: 保持在中央
                height * 0.2,    # y2: 屏幕 20% 位置
                0.3              # 滑動持續(xù)時間(秒)
            )
            print(f"[{count}] {time.strftime('%H:%M:%S')} ? 滑動成功")
            time.sleep(interval)
    except KeyboardInterrupt:
        print(f"\n??  已停止,共執(zhí)行 {count} 次滑動")
    except Exception as e:
        print(f"\n? 發(fā)生錯誤: {e}")
if __name__ == "__main__":
    main()

運行:

python u2_basic_swipe.py

4.2 高級功能腳本

創(chuàng)建 u2_advanced_swipe.py

"""
uiautomator2 高級自動化腳本
功能:
1. 啟動指定應(yīng)用
2. 智能檢測頁面狀態(tài)
3. 支持多種滑動模式
4. 異常處理和自動恢復(fù)
"""
import uiautomator2 as u2
import time
import random
from datetime import datetime
class VideoAutomation:
    def __init__(self, package_name, interval=5, total_count=None):
        """
        初始化視頻自動化控制器
        參數(shù):
        package_name: 應(yīng)用包名
        interval: 滑動間隔(秒)
        total_count: 總滑動次數(shù)(None=無限次)
        """
        self.package_name = package_name
        self.interval = interval
        self.total_count = total_count
        self.device = None
        self.count = 0
        self.width = 0
        self.height = 0
    def connect(self):
        """連接設(shè)備"""
        try:
            self.device = u2.connect()
            self.width, self.height = self.device.window_size()
            print(f"? 已連接設(shè)備: {self.device.info.get('productName', 'Unknown')}")
            print(f"?? 分辨率: {self.width}x{self.height}")
            print(f"?? Android 版本: {self.device.info.get('version', 'Unknown')}")
            return True
        except Exception as e:
            print(f"? 連接設(shè)備失敗: {e}")
            return False
    def start_app(self):
        """啟動應(yīng)用"""
        try:
            print(f"?? 正在啟動應(yīng)用: {self.package_name}")
            self.device.app_start(self.package_name)
            time.sleep(3)  # 等待應(yīng)用啟動
            # 驗證應(yīng)用是否啟動成功
            current = self.device.app_current()
            if current.get('package') == self.package_name:
                print(f"? 應(yīng)用啟動成功")
                return True
            else:
                print(f"??  啟動的應(yīng)用不匹配,當前: {current.get('package')}")
                return False
        except Exception as e:
            print(f"? 啟動應(yīng)用失敗: {e}")
            return False
    def check_app_running(self):
        """檢查應(yīng)用是否在前臺運行"""
        try:
            current = self.device.app_current()
            return current.get('package') == self.package_name
        except:
            return False
    def swipe_up(self):
        """向上滑動(下一個視頻)"""
        try:
            # 使用屏幕中央位置滑動
            x = self.width // 2
            y1 = int(self.height * 0.75)  # 起始位置:75%
            y2 = int(self.height * 0.25)  # 結(jié)束位置:25%
            self.device.swipe(x, y1, x, y2, 0.3)
            self.count += 1
            return True
        except Exception as e:
            print(f"? 滑動失敗: {e}")
            return False
    def swipe_down(self):
        """向下滑動(上一個視頻)"""
        try:
            x = self.width // 2
            y1 = int(self.height * 0.25)
            y2 = int(self.height * 0.75)
            self.device.swipe(x, y1, x, y2, 0.3)
            return True
        except Exception as e:
            print(f"? 滑動失敗: {e}")
            return False
    def random_swipe(self):
        """隨機滑動(模擬人類行為)"""
        # 90% 概率向上,10% 概率向下
        if random.random() < 0.9:
            return self.swipe_up()
        else:
            print("   ↓ 隨機向下滑動")
            return self.swipe_down()
    def should_continue(self):
        """判斷是否繼續(xù)執(zhí)行"""
        if self.total_count is None:
            return True
        return self.count < self.total_count
    def get_random_interval(self):
        """獲取隨機間隔時間(模擬人類)"""
        # 在設(shè)定間隔基礎(chǔ)上 ±20% 浮動
        variation = self.interval * 0.2
        return self.interval + random.uniform(-variation, variation)
    def run(self):
        """運行自動化任務(wù)"""
        if not self.connect():
            return
        if not self.start_app():
            return
        print(f"\n? 平均滑動間隔: {self.interval} 秒(隨機波動)")
        if self.total_count:
            print(f"?? 目標次數(shù): {self.total_count} 次")
        else:
            print(f"?? 持續(xù)運行(按 Ctrl+C 停止)")
        print("-" * 50)
        start_time = time.time()
        try:
            while self.should_continue():
                # 檢查應(yīng)用是否還在前臺
                if not self.check_app_running():
                    print("??  應(yīng)用不在前臺,嘗試重新啟動...")
                    if not self.start_app():
                        break
                # 執(zhí)行滑動
                current_time = datetime.now().strftime('%H:%M:%S')
                print(f"[{self.count + 1}] {current_time} ", end="")
                if self.random_swipe():
                    print("?")
                else:
                    print("? 失敗,繼續(xù)...")
                # 等待隨機間隔
                if self.should_continue():
                    wait_time = self.get_random_interval()
                    time.sleep(wait_time)
        except KeyboardInterrupt:
            print("\n\n??  用戶停止")
        except Exception as e:
            print(f"\n? 發(fā)生錯誤: {e}")
        finally:
            elapsed = time.time() - start_time
            self.print_statistics(elapsed)
    def print_statistics(self, elapsed_time):
        """打印統(tǒng)計信息"""
        print(f"\n{'='*50}")
        print(f"?? 運行統(tǒng)計:")
        print(f"   - 總滑動次數(shù): {self.count}")
        print(f"   - 運行時長: {int(elapsed_time)} 秒 ({int(elapsed_time/60)} 分鐘)")
        if self.count > 0:
            print(f"   - 平均間隔: {elapsed_time/self.count:.1f} 秒")
        print(f"{'='*50}")
def main():
    import argparse
    # 解析命令行參數(shù)
    parser = argparse.ArgumentParser(description='uiautomator2 視頻自動化腳本')
    parser.add_argument('package', help='應(yīng)用包名,如: com.ss.android.ugc.aweme')
    parser.add_argument('-i', '--interval', type=float, default=5.0,
                       help='滑動間隔(秒),默認5秒')
    parser.add_argument('-n', '--count', type=int, default=None,
                       help='滑動次數(shù),不指定則無限循環(huán)')
    args = parser.parse_args()
    # 創(chuàng)建并運行自動化任務(wù)
    automation = VideoAutomation(
        package_name=args.package,
        interval=args.interval,
        total_count=args.count
    )
    automation.run()
if __name__ == "__main__":
    main()

4.3 智能元素定位腳本

創(chuàng)建 u2_smart_control.py

"""
基于 UI 元素的智能控制腳本
功能:通過識別頁面元素來智能操作
"""
import uiautomator2 as u2
import time
class SmartController:
    def __init__(self, package_name):
        self.package_name = package_name
        self.device = u2.connect()
    def start(self):
        """啟動應(yīng)用"""
        self.device.app_start(self.package_name)
        time.sleep(2)
    def wait_and_click(self, text=None, description=None, timeout=10):
        """等待元素出現(xiàn)并點擊"""
        try:
            if text:
                # 通過文本查找并點擊
                self.device(text=text).click(timeout=timeout)
                print(f"? 點擊了: {text}")
                return True
            elif description:
                # 通過描述查找并點擊
                self.device(description=description).click(timeout=timeout)
                print(f"? 點擊了: {description}")
                return True
        except u2.exceptions.UiObjectNotFoundError:
            print(f"??  未找到元素")
            return False
    def swipe_if_video_exists(self):
        """如果檢測到視頻元素就滑動"""
        # 示例:檢測特定 ID 的視頻容器
        if self.device(resourceId="video_container").exists:
            width, height = self.device.window_size()
            self.device.swipe(width//2, height*0.8, width//2, height*0.2, 0.3)
            print("? 檢測到視頻,已滑動")
            return True
        return False
    def auto_handle_popups(self):
        """自動處理彈窗"""
        # 常見彈窗按鈕文本
        close_texts = ["關(guān)閉", "取消", "不感興趣", "跳過", "我知道了"]
        for text in close_texts:
            if self.device(text=text).exists:
                self.device(text=text).click()
                print(f"? 關(guān)閉彈窗: {text}")
                time.sleep(0.5)
                return True
        return False
# 使用示例
if __name__ == "__main__":
    controller = SmartController("com.ss.android.ugc.aweme")
    controller.start()
    # 自動處理啟動頁彈窗
    time.sleep(2)
    controller.auto_handle_popups()
    # 持續(xù)滑動
    for i in range(10):
        controller.swipe_if_video_exists()
        time.sleep(5)

五、運行指南

5.1 基礎(chǔ)腳本運行

# 運行基礎(chǔ)滑動腳本
python u2_basic_swipe.py

5.2 高級腳本運行

抖音自動刷視頻(每5秒一次):

python u2_advanced_swipe.py com.ss.android.ugc.aweme

快手自動刷視頻(每8秒一次,共50次):

python u2_advanced_swipe.py com.smile.gifmaker -i 8 -n 50

B站自動刷視頻(每3秒一次):

python u2_advanced_swipe.py tv.danmaku.bili -i 3

5.3 查看幫助

python u2_advanced_swipe.py -h

六、WiFi 無線連接配置

6.1 配置步驟

1. 確保手機和電腦在同一 WiFi 網(wǎng)絡(luò)

2. 通過 USB 啟用 WiFi 調(diào)試:

# 查看手機 IP 地址
adb shell ip addr show wlan0
# 啟用 WiFi ADB(端口 5555)
adb tcpip 5555
# 記下手機 IP 地址(如 192.168.1.100)

3. 連接 WiFi:

# 斷開 USB 線
adb connect 192.168.1.100:5555

4. 在腳本中使用 WiFi 連接:

import uiautomator2 as u2
# 使用 IP 地址連接
d = u2.connect('192.168.1.100')

6.2 WiFi 連接優(yōu)勢

  • 無需 USB 線,更自由
  • 可以同時控制多臺手機
  • 適合長時間運

七、UI 元素定位技巧

7.1 查看頁面元素

安裝 weditor(UI 查看器):

pip install weditor

啟動 weditor:

python -m weditor

瀏覽器會自動打開 http://localhost:17310

使用方法:

  1. 輸入設(shè)備 IP 或序列號,點擊 Connect
  2. 點擊 Dump Hierarchy 獲取當前頁面結(jié)構(gòu)
  3. 點擊元素查看屬性(text、resourceId、className 等)
  4. 可以實時測試定位表達式

7.2 常用定位方法

import uiautomator2 as u2
d = u2.connect()
# 通過文本定位
d(text="立即登錄").click()
# 通過文本包含
d(textContains="登錄").click()
# 通過 resourceId 定位
d(resourceId="com.app:id/button").click()
# 通過 className 定位
d(className="android.widget.Button").click()
# 通過 description 定位
d(description="確認按鈕").click()
# 組合定位
d(className="android.widget.Button", text="確認").click()
# 索引定位(多個相同元素時)
d(className="android.widget.Button")[0].click()  # 第一個按鈕
d(className="android.widget.Button")[1].click()  # 第二個按鈕

7.3 等待元素出現(xiàn)

# 等待元素出現(xiàn)(最多等待10秒)
d(text="加載完成").wait(timeout=10)
# 等待元素消失
d(text="加載中...").wait_gone(timeout=10)
# 判斷元素是否存在
if d(text="登錄").exists:
    print("找到登錄按鈕")
# 獲取元素信息
info = d(text="登錄").info
print(info)

八、高級功能示例

8.1 自動點贊腳本

"""
視頻自動點贊腳本
"""
import uiautomator2 as u2
import time
d = u2.connect()
d.app_start("com.ss.android.ugc.aweme")
time.sleep(3)
for i in range(10):
    # 雙擊屏幕點贊(適用于抖音)
    width, height = d.window_size()
    d.double_click(width//2, height//2)
    print(f"??  點贊第 {i+1} 次")
    time.sleep(1)
    # 滑動到下一個視頻
    d.swipe(width//2, height*0.8, width//2, height*0.2, 0.3)
    time.sleep(5)

8.2 自動關(guān)注腳本

"""
自動關(guān)注作者腳本
"""
import uiautomator2 as u2
import time
d = u2.connect()
d.app_start("com.ss.android.ugc.aweme")
time.sleep(3)
for i in range(5):
    # 查找并點擊關(guān)注按鈕
    if d(text="關(guān)注").exists:
        d(text="關(guān)注").click()
        print(f"? 關(guān)注第 {i+1} 個作者")
    elif d(textContains="關(guān)注").exists:
        d(textContains="關(guān)注").click()
        print(f"? 關(guān)注第 {i+1} 個作者")
    else:
        print("??  未找到關(guān)注按鈕")
    time.sleep(2)
    # 滑到下一個視頻
    width, height = d.window_size()
    d.swipe(width//2, height*0.8, width//2, height*0.2, 0.3)
    time.sleep(5)

8.3 截圖并保存

"""
定時截圖腳本
"""
import uiautomator2 as u2
import time
from datetime import datetime
d = u2.connect()
d.app_start("com.ss.android.ugc.aweme")
for i in range(10):
    # 生成帶時間戳的文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"
    # 截圖
    d.screenshot(filename)
    print(f"?? 已保存截圖: {filename}")
    # 滑動
    width, height = d.window_size()
    d.swipe(width//2, height*0.8, width//2, height*0.2, 0.3)
    time.sleep(5)

8.4 監(jiān)控屏幕變化

"""
監(jiān)控屏幕變化腳本
"""
import uiautomator2 as u2
import time
d = u2.connect()
# 獲取初始截圖
last_screen = d.screenshot()
while True:
    time.sleep(1)
    current_screen = d.screenshot()
    # 簡單對比(可用圖像相似度算法優(yōu)化)
    if current_screen != last_screen:
        print("?? 屏幕內(nèi)容已變化")
        last_screen = current_screen

九、故障排查

9.1 “ConnectionError: Unable to connect to device”

解決方案:

# 1. 檢查 ADB 連接
adb devices
# 2. 重新初始化 uiautomator2
python -m uiautomator2 init
# 3. 檢查 ATX-Agent 是否運行
adb shell ps | grep atx
# 4. 重啟 ATX-Agent
adb shell am force-stop com.github.uiautomator
python -m uiautomator2 init

9.2 元素定位失敗

解決方案:

  1. 使用 weditor 查看實際元素屬性
  2. 檢查元素是否在屏幕可見區(qū)域
  3. 增加等待時間
  4. 使用更精確的定位方式
# 添加等待
d(text="按鈕").wait(timeout=10)
# 嘗試不同定位方式
if not d(text="登錄").exists:
    d(textContains="登錄").click()

9.3 “UiObjectNotFoundError”

解決方案:

# 使用異常處理
try:
    d(text="按鈕").click()
except u2.exceptions.UiObjectNotFoundError:
    print("元素不存在,跳過")
# 或先判斷
if d(text="按鈕").exists:
    d(text="按鈕").click()

9.4 操作響應(yīng)慢

解決方案:

# 設(shè)置操作超時時間
d.settings['operation_delay'] = (0, 0)  # 點擊前后延遲
d.settings['operation_delay_methods'] = ['click', 'swipe']
# 設(shè)置 implicitly_wait
d.implicitly_wait(10)  # 隱式等待10秒

9.5 WiFi 連接斷開

解決方案:

# 重新連接
adb connect <手機IP>:5555
# 保持連接
adb connect <手機IP>:5555
adb -s <手機IP>:5555 shell settings put global stay_on_while_plugged_in 7

十、性能優(yōu)化

10.1 加快操作速度

# 關(guān)閉等待時間
d.settings['wait_timeout'] = 10  # 全局等待超時
d.settings['operation_delay'] = (0, 0)  # 操作延遲
# 使用 shell 命令代替高級 API
d.shell("input swipe 500 1500 500 500 100")  # 更快

10.2 減少資源占用

# 不需要截圖時關(guān)閉
# 使用 shell 命令代替截圖檢查
# 批量操作
for i in range(100):
    d.swipe(500, 1500, 500, 500, 0.1)  # 減少滑動時間

10.3 異步操作

import asyncio
import uiautomator2 as u2
async def swipe_task(device, count):
    for i in range(count):
        width, height = device.window_size()
        device.swipe(width//2, height*0.8, width//2, height*0.2, 0.3)
        await asyncio.sleep(3)
async def main():
    d = u2.connect()
    await swipe_task(d, 10)
asyncio.run(main())

十一、完整項目結(jié)構(gòu)

phone-automation-u2/
├── test_u2.py                  # 測試連接
├── u2_basic_swipe.py           # 基礎(chǔ)滑動
├── u2_advanced_swipe.py        # 高級滑動
├── u2_smart_control.py         # 智能控制
├── screenshots/                # 截圖目錄
│   └── screenshot_*.png
└── logs/                       # 日志目錄
    └── automation.log

十二、uiautomator2 vs ADB 對比

功能uiautomator2ADB
元素定位? 支持? 不支持
應(yīng)用管理? 便捷?? 需命令
WiFi 連接? 簡單?? 需配置
學(xué)習(xí)曲線?? 中等? 簡單
性能?? 中等? 快速
功能豐富度? 豐富?? 基礎(chǔ)
配置復(fù)雜度?? 需初始化? 簡單

十三、實戰(zhàn)案例

13.1 完整的抖音自動刷視頻腳本

"""
抖音自動刷視頻完整腳本
功能:
- 自動啟動抖音
- 智能跳過廣告
- 隨機間隔滑動
- 異常自動恢復(fù)
"""
import uiautomator2 as u2
import time
import random
from datetime import datetime
class DouyinAutomation:
    def __init__(self):
        self.device = u2.connect()
        self.package = "com.ss.android.ugc.aweme"
        self.count = 0
    def start(self):
        """啟動抖音"""
        print("?? 啟動抖音...")
        self.device.app_start(self.package)
        time.sleep(3)
        self.handle_popups()
    def handle_popups(self):
        """處理啟動彈窗"""
        close_buttons = ["關(guān)閉", "跳過", "我知道了", "取消"]
        for btn in close_buttons:
            if self.device(text=btn).exists:
                self.device(text=btn).click()
                print(f"? 關(guān)閉彈窗: {btn}")
                time.sleep(0.5)
    def swipe_next(self):
        """滑到下一個視頻"""
        width, height = self.device.window_size()
        # 添加輕微隨機偏移
        x = width // 2 + random.randint(-50, 50)
        y1 = int(height * 0.75) + random.randint(-20, 20)
        y2 = int(height * 0.25) + random.randint(-20, 20)
        duration = random.uniform(0.25, 0.35)
        self.device.swipe(x, y1, x, y2, duration)
        self.count += 1
    def check_status(self):
        """檢查應(yīng)用狀態(tài)"""
        current = self.device.app_current()
        if current.get('package') != self.package:
            print("??  應(yīng)用不在前臺,重新啟動")
            self.start()
            return False
        return True
    def run(self, duration_minutes=30):
        """運行指定時長"""
        self.start()
        end_time = time.time() + duration_minutes * 60
        print(f"?? 開始刷視頻,持續(xù) {duration_minutes} 分鐘")
        print("-" * 50)
        try:
            while time.time() < end_time:
                if not self.check_status():
                    continue
                # 滑動
                timestamp = datetime.now().strftime('%H:%M:%S')
                print(f"[{self.count + 1}] {timestamp} ?")
                self.swipe_next()
                # 隨機間隔 4-8 秒
                interval = random.uniform(4, 8)
                time.sleep(interval)
        except KeyboardInterrupt:
            print("\n??  用戶停止")
        finally:
            print(f"\n?? 總共觀看 {self.count} 個視頻")
if __name__ == "__main__":
    automation = DouyinAutomation()
    automation.run(duration_minutes=10)  # 運行10分鐘

十四、總結(jié)

恭喜完成 uiautomator2 教程!你現(xiàn)在已經(jīng)掌握:

? uiautomator2 環(huán)境搭建和初始化
? 設(shè)備連接(USB 和 WiFi)
? 基礎(chǔ)操作(點擊、滑動、輸入等)
? UI 元素定位技巧
? 應(yīng)用管理和控制
? 高級功能實現(xiàn)
? 異常處理和優(yōu)化

uiautomator2 優(yōu)勢:

  • 功能強大,支持復(fù)雜交互
  • 可以精確定位 UI 元素
  • 支持無線連接
  • Python API 友好

適用場景:

  • 需要元素定位的自動化
  • 復(fù)雜交互邏輯
  • 應(yīng)用測試
  • UI 自動化操作

下一步建議:

  • 學(xué)習(xí)圖像識別(OpenCV)
  • 研究 OCR 文字識別
  • 探索 AI 輔助自動化
  • 學(xué)習(xí) Appium 實現(xiàn)跨平臺自動化

參考資源:

  • uiautomator2 文檔:https://github.com/openatx/uiautomator2
  • weditor 工具:https://github.com/alibaba/web-editor
  • Android UI 文檔:https://developer.android.com/reference/android/support/test/uiautomator/package-summary

到此這篇關(guān)于Python+uiautomator2手機自動化控制的文章就介紹到這了,更多相關(guān)Python uiautomator2手機自動化控制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解決python中畫圖時x,y軸名稱出現(xiàn)中文亂碼的問題

    解決python中畫圖時x,y軸名稱出現(xiàn)中文亂碼的問題

    今天小編就為大家分享一篇解決python中畫圖時x,y軸名稱出現(xiàn)中文亂碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • Python中try?except語句及實際應(yīng)用詳細解釋

    Python中try?except語句及實際應(yīng)用詳細解釋

    在Python中try和except是用于異常處理的關(guān)鍵字,它們可以捕獲程序運行時可能出現(xiàn)的錯誤,從而避免程序崩潰,這篇文章主要介紹了Python中try?except語句及實際應(yīng)用的相關(guān)資料,需要的朋友可以參考下
    2025-04-04
  • 玩轉(zhuǎn)Python圖像處理之二值圖像腐蝕詳解

    玩轉(zhuǎn)Python圖像處理之二值圖像腐蝕詳解

    這篇文章主要給大家介紹了關(guān)于Python圖像處理之二值圖像腐蝕的相關(guān)資料,對原圖進行二值化后,選擇不同的結(jié)構(gòu)元素對其進行膨脹和腐蝕運算處理,并仿真出圖像結(jié)果,需要的朋友可以參考下
    2021-09-09
  • 解決pycharm無法刪除invalid interpreter(無效解析器)的問題

    解決pycharm無法刪除invalid interpreter(無效解析器)的問題

    這篇文章主要介紹了pycharm無法刪除invalid interpreter(無效解析器)的問題,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-07-07
  • Python中scrapy下載保存圖片的示例

    Python中scrapy下載保存圖片的示例

    在日常爬蟲練習(xí)中,我們爬取到的數(shù)據(jù)需要進行保存操作,在scrapy中我們可以使用ImagesPipeline這個類來進行相關(guān)操作,本文主要介紹了scrapy下載保存圖片,感興趣的可以了解一下
    2021-07-07
  • python dlib人臉識別代碼實例

    python dlib人臉識別代碼實例

    這篇文章主要介紹了python dlib人臉識別,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • Python 通過URL打開圖片實例詳解

    Python 通過URL打開圖片實例詳解

    這篇文章主要介紹了Python 通過URL打開圖片實例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • python MultipartEncoder傳輸zip文件實例

    python MultipartEncoder傳輸zip文件實例

    這篇文章主要介紹了python MultipartEncoder傳輸zip文件實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • 淺談python多進程共享變量Value的使用tips

    淺談python多進程共享變量Value的使用tips

    今天小編就為大家分享一篇淺談python多進程共享變量Value的使用tips,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • python Canny邊緣檢測算法的實現(xiàn)

    python Canny邊緣檢測算法的實現(xiàn)

    這篇文章主要介紹了python Canny邊緣檢測算法的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04

最新評論

芷江| 张家口市| 新野县| 称多县| 舟曲县| 桦川县| 浮梁县| 梧州市| 黎川县| 醴陵市| 达拉特旗| 永年县| 临泽县| 乌拉特前旗| 衡东县| 怀远县| 高邑县| 电白县| 金秀| 历史| 三原县| 阳西县| 乌苏市| 乌拉特中旗| 临沭县| 苍南县| 惠水县| 新余市| 香格里拉县| 宁陵县| 瓦房店市| 靖西县| 资兴市| 名山县| 宁明县| 喀什市| 龙门县| 湖州市| 长兴县| 开原市| 柘城县|