You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Flask服务器点击HTML按钮触发Appium脚本在本地设备运行?

解决方案

1. 重构Appium脚本为可调用模块

把你的多函数Appium脚本封装成一个带参数的入口函数,这样Flask只需调用这一个入口就能执行完整流程。示例脚本appium_test.py:

# appium_test.py
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

def run_full_test(target_path):
    # 初始化Appium驱动(根据你的设备/APP配置修改)
    desired_caps = {
        "platformName": "Android",
        "deviceName": "你的设备名",
        "appPackage": "目标APP包名",
        "appActivity": "目标启动Activity",
        "noReset": True
    }
    driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
    
    try:
        # 按顺序执行所有测试步骤
        navigate_to_target(driver, target_path)
        execute_test_step1(driver)
        execute_test_step2(driver)
        # 其他测试函数...
    finally:
        driver.quit()

def navigate_to_target(driver, path):
    # 用传入的path参数执行页面导航
    driver.find_element(AppiumBy.ID, "输入框ID").send_keys(path)
    driver.find_element(AppiumBy.ID, "跳转按钮ID").click()

def execute_test_step1(driver):
    # 测试步骤1逻辑
    pass

def execute_test_step2(driver):
    # 测试步骤2逻辑
    pass

2. 修改Flask后端逻辑

在flask_server.py中让默认路由/同时处理GET(显示表单)和POST(触发脚本)请求,用异步线程执行Appium脚本,避免阻塞Flask服务:

# flask_server.py
from flask import Flask, render_template, request
import threading
from appium_test import run_full_test

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    message = ""
    if request.method == 'POST':
        target_path = request.form.get('target_path', '').strip()
        if target_path:
            # 启动线程异步执行脚本,不阻塞Flask响应
            threading.Thread(target=run_full_test, args=(target_path,), daemon=True).start()
            message = "测试已启动,请查看设备状态"
        else:
            message = "请输入有效路径"
    return render_template('index.html', message=message)

if __name__ == '__main__':
    app.run(debug=True)

3. 编写HTML模板

在templates文件夹下创建index.html,实现参数输入和提交按钮:

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>触发Appium测试</title>
</head>
<body>
    <h2>Appium测试触发工具</h2>
    {% if message %}
        <p style="color: #2ecc71;">{{ message }}</p>
    {% endif %}
    <form method="POST">
        <div>
            <label>目标路径:</label>
            <input type="text" name="target_path" placeholder="输入要跳转的路径">
        </div>
        <button type="submit" style="margin-top: 10px;">启动测试</button>
    </form>
</body>
</html>

关键注意事项

  • 确保Appium服务已启动:终端执行appium命令,等待服务监听4723端口
  • 设备正常连接:用adb devices确认设备被识别
  • 线程的daemon=True配置可确保Flask关闭时脚本线程自动终止,避免残留进程
  • 若需获取脚本运行结果,可通过队列、临时文件或数据库存储状态,再在页面添加轮询逻辑展示

内容的提问来源于stack exchange,提问作者Saif Nasir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:00:55