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

Appium Selenium中OTP输入问题求助:send_keys无效且无法用XPath

OTP输入问题解决方法

针对无法用send_keys输入OTP、且不推荐使用XPath的情况,可尝试以下几种方案:

  • 优先使用Accessibility ID定位
    通过Appium Inspector查看OTP输入框的accessibility id属性,用该属性定位元素后输入。如果是多格输入框(常见6个单字符输入框),循环定位每个框并输入对应字符:

    from appium.webdriver.common.appiumby import AppiumBy
    
    otp_boxes = driver.find_elements(AppiumBy.ACCESSIBILITY_ID, "otp_box")
    for box, char in zip(otp_boxes, "123456"):
        box.send_keys(char)
    
  • Android平台用UiAutomator定位
    利用Android原生UiSelector语法定位元素,比如根据输入框类名筛选:

    otp_fields = driver.find_elements(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().className("android.widget.EditText")')
    for idx, char in enumerate("123456"):
        otp_fields[idx].send_keys(char)
    
  • 坐标点击+ADB输入
    若无法定位元素,可通过坐标点击每个输入框位置,再用ADB命令输入字符(需根据实际页面调整坐标参数):

    base_x = 150
    y_pos = 600
    interval = 70  # 每个输入框的x轴间隔
    
    for i, char in enumerate("123456"):
        driver.tap([(base_x + i*interval, y_pos)])
        driver.execute_script('mobile: shell', {'command': f'input text {char}'})
    
  • 直接执行ADB全局输入
    确保OTP输入框已获取焦点后,直接用ADB命令输入完整OTP:

    driver.execute_script('mobile: shell', {'command': 'input text "123456"'})
    
  • 等待元素可交互后再输入
    若send_keys无效是因为元素未加载完成,添加等待逻辑:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    otp_field = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((AppiumBy.ACCESSIBILITY_ID, "otp_input"))
    )
    otp_field.send_keys("123456")
    

内容的提问来源于stack exchange,提问作者My Explore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:10:06