Bootstrap

appium文本输入的多种形式

目录

一、send_keys方法

二、press_keycode方法

三、subprocess方法直接通过adb命令输入


一、send_keys方法

这个是最常用的方法,不过通常使用时要使用聚焦,也就是先点击后等待:

element = wait.until(EC.presence_of_element_located((By.XPATH,
                                                     r'//android.widget.EditText[@text="a"])')))
element.click()  # 获取焦点
element.send_keys("13488474661")  # 输入文本

但这种方式在处理某些输入框时,会报异常,类似这种,如果反复切换元素仍不能解决,就要考虑换方法了:

selenium.common.exceptions.InvalidElementStateException: Message: ACTION_SET_PROGRESS has failed on the element 'android.view.accessibility.AccessibilityNodeInfo@17c97; boundsInParent: Rect(0, 0 - 269, 36); boundsInScreen: Rect(201, 717 - 1008, 825); packageName: uni.UNIDCC1D16; className: android.widget.EditText; text: ; error: null; maxTextLength: -1; contentDescription: null; tooltipText: null; viewIdResName: null; checkable: false; checked: false; focusable: true; focused: true; selected: false; clickable: true; longClickable: false; contextClickable: false; enabled: true; password: false; scrollable: false; importantForAccessibility: false; visible: true; actions: [AccessibilityAction: ACTION_NEXT_HTML_ELEMENT - null, AccessibilityAction: ACTION_PREVIOUS_HTML_ELEMENT - null, AccessibilityAction: ACTION_SHOW_ON_SCREEN - null, AccessibilityAction: ACTION_CONTEXT_CLICK - null, AccessibilityAction: ACTION_SET_TEXT - null, AccessibilityAction: ACTION_PASTE - null, AccessibilityAction: ACTION_UNKNOWN - null, AccessibilityAction: ACTION_CLEAR_FOCUS - null, AccessibilityAction: ACTION_ACCESSIBILITY_FOCUS - null, AccessibilityAction: ACTION_CLICK - null, AccessibilityAction: ACTION_SET_PROGRESS - null]'. Did you interact with the correct element?
Stacktrace:

二、press_keycode方法

以下方法,可使输入框聚焦后直接输入即可,亦可以解决上面元素定位异常send_keys的问题:

            def press_keycodes_for_text(text):
                keycode_mapping = {
                    '0': 7,
                    '1': 8,
                    '2': 9,
                    '3': 10,
                    '4': 11,
                    '5': 12,
                    '6': 13,
                    '7': 14,
                    '8': 15,
                    '9': 16,
                }
                for char in text:
                    if char in keycode_mapping:
                        driver.press_keycode(keycode_mapping[char])


            # 输入示例
            press_keycodes_for_text("13488474661")

三、subprocess方法直接通过adb命令输入

引用subprocess包直接写入对应的内容即可,前提也是先聚焦文本框:

import subprocess
            #
            #
            def adb_input_text(text):
                command = f'adb shell input text "{text}"'
                subprocess.run(command, shell=True)


            # 调用示例
            adb_input_text("13488474661")

;