Appium自动化测试常见问题

问题

模拟器上安装的雪球,通过python运行appium自动化脚本,雪球会自动退出,请问有没有哪位大佬遇见过?

报错信息

D:\AutoTest\Web\venv_hjh\Scripts\python.exe "E:\software_install_package\pycharm\PyCharm Community Edition 2022.1.3\plugins\python-ce\helpers\pycharm\_jb_pytest_runner.py" --target test_xueqiu_search.py::TestXueqiuSearch
Testing started at 14:15 ...
Launching pytest with arguments test_xueqiu_search.py::TestXueqiuSearch --no-header --no-summary -q in D:\AutoTest\App

============================= test session starts =============================
collecting ... collected 1 item

test_xueqiu_search.py::TestXueqiuSearch::test_search ERROR               [100%]
test setup failed
self = <class 'App.test_xueqiu_search.TestXueqiuSearch'>

    def setup_class(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        # desired_caps['platformVersion'] = '12'
        desired_caps['deviceName'] = 'emulator-5554'
        desired_caps['appPackage'] = 'com.xueqiu.android'
        desired_caps['appActivity'] = '.view.WelcomeActivityAlias'
        desired_caps['noReset'] = 'true'
>       self.driver = webdriver.Remote('http://localhost:4723/wd/hub', options=UiAutomator2Options().load_capabilities(desired_caps))

test_xueqiu_search.py:19: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\Web\venv_hjh\lib\site-packages\appium\webdriver\webdriver.py:229: in __init__
    super().__init__(
..\Web\venv_hjh\lib\site-packages\selenium\webdriver\remote\webdriver.py:212: in __init__
    self.start_session(capabilities)
..\Web\venv_hjh\lib\site-packages\appium\webdriver\webdriver.py:318: in start_session
    response = self.execute(RemoteCommand.NEW_SESSION, w3c_caps)
..\Web\venv_hjh\lib\site-packages\selenium\webdriver\remote\webdriver.py:354: in execute
    self.error_handler.check_response(response)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x00000206B5AC3610>
response = {'status': 500, 'value': '{"value":{"error":"unknown error","message":"An unknown server-side error occurred while pro...s\\\\app\\\\node_modules\\\\appium\\\\node_modules\\\\appium-base-driver\\\\lib\\\\protocol\\\\protocol.js:384:37)"}}'}

    def check_response(self, response: Dict[str, Any]) -> None:
        """Checks that a JSON response from the WebDriver does not have an
        error.
    
        :Args:
         - response - The JSON response from the WebDriver server as a dictionary
           object.
    
        :Raises: If the response contains an error message.
        """
        status = response.get("status", None)
        if not status or status == ErrorCode.SUCCESS:
            return
        value = None
        message = response.get("message", "")
        screen: str = response.get("screen", "")
        stacktrace = None
        if isinstance(status, int):
            value_json = response.get("value", None)
            if value_json and isinstance(value_json, str):
                import json
    
                try:
                    value = json.loads(value_json)
                    if len(value) == 1:
                        value = value["value"]
                    status = value.get("error", None)
                    if not status:
                        status = value.get("status", ErrorCode.UNKNOWN_ERROR)
                        message = value.get("value") or value.get("message")
                        if not isinstance(message, str):
                            value = message
                            message = message.get("message")
                    else:
                        message = value.get("message", None)
                except ValueError:
                    pass
    
        exception_class: Type[WebDriverException]
        e = ErrorCode()
        error_codes = [item for item in dir(e) if not item.startswith("__")]
        for error_code in error_codes:
            error_info = getattr(ErrorCode, error_code)
            if isinstance(error_info, list) and status in error_info:
                exception_class = getattr(ExceptionMapping, error_code, WebDriverException)
                break
        else:
            exception_class = WebDriverException
    
        if not value:
            value = response["value"]
        if isinstance(value, str):
            raise exception_class(value)
        if message == "" and "message" in value:
            message = value["message"]
    
        screen = None  # type: ignore[assignment]
        if "screen" in value:
            screen = value["screen"]
    
        stacktrace = None
        st_value = value.get("stackTrace") or value.get("stacktrace")
        if st_value:
            if isinstance(st_value, str):
                stacktrace = st_value.split("\n")
            else:
                stacktrace = []
                try:
                    for frame in st_value:
                        line = frame.get("lineNumber", "")
                        file = frame.get("fileName", "<anonymous>")
                        if line:
                            file = f"{file}:{line}"
                        meth = frame.get("methodName", "<anonymous>")
                        if "className" in frame:
                            meth = f"{frame['className']}.{meth}"
                        msg = "    at %s (%s)"
                        msg = msg % (meth, file)
                        stacktrace.append(msg)
                except TypeError:
                    pass
        if exception_class == UnexpectedAlertPresentException:
            alert_text = None
            if "data" in value:
                alert_text = value["data"].get("text")
            elif "alert" in value:
                alert_text = value["alert"].get("text")
            raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
>       raise exception_class(message, screen, stacktrace)
E       selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: Cannot start the 'com.xueqiu.android' application. Visit https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/activity-startup.md for troubleshooting. Original error: Error executing adbExec. Original error: 'Command 'F:\\Android_sdk\\platform-tools\\adb.exe -P 5037 -s 127.0.0.1\:16384 shell am start -W -n com.xueqiu.android/.view.WelcomeActivityAlias -S -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -f 0x10200000' timed out after 20000ms'. Try to increase the 20000ms adb execution timeout represented by 'adbExecTimeout' capability
E       Stacktrace:
E       UnknownError: An unknown server-side error occurred while processing the command. Original error: Cannot start the 'com.xueqiu.android' application. Visit https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/activity-startup.md for troubleshooting. Original error: Error executing adbExec. Original error: 'Command 'F:\\Android_sdk\\platform-tools\\adb.exe -P 5037 -s 127.0.0.1\:16384 shell am start -W -n com.xueqiu.android/.view.WelcomeActivityAlias -S -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -f 0x10200000' timed out after 20000ms'. Try to increase the 20000ms adb execution timeout represented by 'adbExecTimeout' capability
E           at getResponseForW3CError (C:\Program Files\Appium\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\protocol\errors.js:804:9)
E           at asyncHandler (C:\Program Files\Appium\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\protocol\protocol.js:384:37)

..\Web\venv_hjh\lib\site-packages\selenium\webdriver\remote\errorhandler.py:229: WebDriverException

环境

###执行脚本

import time


from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy


class TestXueqiuSearch:

    def setup_class(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        # desired_caps['platformVersion'] = '12'
        desired_caps['deviceName'] = 'emulator-5554'
        desired_caps['appPackage'] = 'com.xueqiu.android'
        desired_caps['appActivity'] = '.view.WelcomeActivityAlias'
        desired_caps['noReset'] = 'true'
        self.driver = webdriver.Remote('http://localhost:4723/wd/hub', options=UiAutomator2Options().load_capabilities(desired_caps))
        self.driver.implicitly_wait(60)
    def teardown_class(self):
        self.driver.quit()

    def test_search(self):
        # search_box = self.driver.find_element(AppiumBy.XPATH,'//*[@resource-id="com.xueqiu.android:id/ll_header_view"]//android.widget.TextView')
        # print(search_box)
        self.driver.find_element(AppiumBy.ID,
                                 'com.xueqiu.android:id/tv_banner').click()
        time.sleep(30)

def test_search(self):
“”"
1. 判断搜索框的是否可用,并查看搜索框 name 属性值,并获取搜索框坐标,以及它的宽高
2. 点击搜索框
3. 向搜索框输入:alibaba
4. 判断【阿里巴巴】是否可见
如果可见,打印“搜索成功”
如果不可见,打印“搜索失败
:return:
“”"
# 1. 判断搜索框的是否可用,并查看搜索框 name 属性值,并获取搜索框坐标,以及它的宽高
search_key = “alibaba”
searchbox_ele = self.driver.find_element(AppiumBy.ID, “com.xueqiu.android:id/home_search”)
# 先判断一下搜索框是否可用
if searchbox_ele.is_enabled():
# 查看搜索框属性
searchbox_text = searchbox_ele.text
print(f"首页搜索框的 text:{searchbox_text}“)
searchbox_location = searchbox_ele.location
print(f"首页搜索框的 location坐标为:{searchbox_location}”)
searchbox_size = searchbox_ele.size
print(f"首页搜索框的 size 宽高:{searchbox_size}")
# 2. 点击搜索框
searchbox_ele.click()
# 3. 向搜索框输入:alibaba
self.driver.find_element(
AppiumBy.ID,
“com.xueqiu.android:id/search_input_text”
).send_keys(search_key)
# 4. 判断【阿里巴巴】是否可见
# 如果可见,打印“搜索成功”
# 如果不可见,打印“搜索失败
alibaba_element = self.driver.find_element(
AppiumBy.XPATH,
“//*[@text=‘阿里巴巴’]”
)
result = alibaba_element.is_displayed()
print(result)
if result == True:
print(“搜索成功”)
else:
print(“搜索失败”)
assert result == True
else:
print(“搜索框不可用”)
assert False

这样写试试

我这是能跑通的,如果还不行,检查下 appium inspector 是否能正常连接

你是说这段脚本在你那边是能正常执行成功的吗?如果是可能就真的还是我电脑有问题了

目前主要是会闪退,都进不去

对,我这可以,用你的代码

可能真的是电脑性能的问题,本来模拟器很消耗内存了已经

你重新跑脚本,看appium server的日志。
看起来是这里有问题。


也是报500


你把这段复制出来查一下,adbExec

你画线的 是说adb执行超时导致的吗?

看日志是这样的,很有可能

所以结合上面老师说的,有可能就是我电脑太卡了 :sob:

哈哈哈哈:joy: