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

如何将Python版Appium WebDriver同步代码转换为异步代码?

同步Appium-Python代码转异步模式的方法

可行性说明

完全可行,Appium Python官方客户端提供了异步WebDriver实现,核心是用异步版本的WebDriver替代同步实现,配合asyncio框架处理异步逻辑,所有IO相关操作改为异步调用即可。

关键转换要点

  • 替换同步WebDriver:导入appium.webdriver.async_webdriver.AsyncWebDriver,替代原同步的webdriver
  • 异步操作标记:所有WebDriver相关操作(连接、查找元素、点击、设置等待)前添加await关键字
  • 异步函数封装:将核心逻辑放到异步函数中,通过asyncio.run()启动执行

转换后的完整代码

import asyncio
from appium.webdriver.async_webdriver import AsyncWebDriver
from appium.webdriver.common.appiumby import AppiumBy


desired_caps = {
    "app": "/home/ubuntu/mobile_automation/sample.apk",
    "platformName": "Android",
    "deviceName": "ubuntu",
    "ignoreHiddenApiPolicyError": "true",
    # "appium:udid": "emulator-5554",
    "unicodeKeyboard": True,
    "resetKeyboard": True,
    "autoGrantPermissions": True,
    "adbExecTimeout": 60000,
    "headless": True
}

async def main():
    try:
        # 异步连接Appium服务器并启动应用
        driver = await AsyncWebDriver.create('http://127.0.0.1:4723/wd/hub', desired_caps)
        await driver.implicitly_wait(10)

        # 异步查找元素并点击
        bank_login_button = await driver.find_element(by=AppiumBy.ID, value='com.indigo.sample:id/btn_register_login')
        await bank_login_button.click()
        print("Webdriver 已连接")
        
        # 按需异步关闭driver
        # await driver.quit()
    except Exception as e:
        print(f"执行出错: {str(e)}")

if __name__ == "__main__":
    asyncio.run(main())

额外注意事项

  • 确保appium-python-client版本≥2.0,旧版本对异步支持不完善
  • 所有涉及WebDriver的IO操作必须加await,否则仅返回协程对象,不会实际执行
  • 异常处理逻辑与同步代码一致,直接在异步函数内捕获即可

内容的提问来源于stack exchange,提问作者Mohanraj M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:05:26