selenium执行报错:response = {‘status‘: 500, ‘value‘: ‘{“value“:{“data“:{“text“:“HTTP 错误 : 302Foun

selenum的代码如下:

import pytest
from selenium import webdriver
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from time import sleep


class Test_错误的登录:

    def test_UI_0001(self):
        print('\n用例UI_0001')
        driver = webdriver.Chrome()
        driver.implicitly_wait(10)

        driver.get("http://127.0.0.1/mgr/index.html")
        # driver.find_element(By.ID, 'username').send_keys('')
        sleep(3)
        driver.find_element(By.ID, 'password').send_keys('88888888')
        sleep(3)
        driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click()
        sleep(2)

        alertText = driver.switch_to.alert.text
        print(alertText)

        assert alertText == '请输入用户名'

执行报错:

python中selenium执行报错:response = {‘status‘: 500, ‘value‘: ‘{“value“:{“data“:{“text“:“HTTP 错误 : 302Found

====================================================================== test session starts ======================================================================
platform win32 -- Python 3.8.3, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 -- E:\tools\Andconda\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.8.3', 'Platform': 'Windows-10-10.0.19041-SP0', 'Packages': {'pytest': '5.4.3', 'py': '1.9.0', 'pluggy': '0.13.1'}, 'Plugins': {'html': '3.
1.1', 'metadata': '2.0.1', 'Faker': '13.3.4'}, 'JAVA_HOME': 'E:\\tools\\Java\\jdk1.8.0_201'}
rootdir: E:\12Python自动化测试\白月黑羽\自动化测试\UI_pytest
plugins: html-3.1.1, metadata-2.0.1, Faker-13.3.4
collected 4 items

cases/登录/test_错误登录.py::Test_错误密码::test_C001001
#### 初始化-目录甲

 *** 初始化-模块 ***

 === 初始化-类 ===

 --- 初始化-方法  ---

用例C001001
PASSED
 --- 清除  -方法 ---

cases/登录/test_错误登录.py::Test_错误密码::test_C001002
 --- 初始化-方法  ---

用例C001002
PASSED
 --- 清除  -方法 ---

cases/登录/test_错误登录.py::Test_错误密码::test_C001003
 --- 初始化-方法  ---

用例C001003
FAILED
 --- 清除  -方法 ---

 === 清除 - 类 ===

 ***   清除-模块 ***

cases/登录/test_错误登录_实战.py::Test_错误的登录::test_UI_0001
用例UI_0001

DevTools listening on ws://127.0.0.1:34075/devtools/browser/ab2ee8c7-ecf9-48d7-984b-5ffcb1f06f40
FAILED
#### 清除-目录甲


=========================================================================== FAILURES ============================================================================ 
____________________________________________________________________ Test_错误密码.test_C001003 __________________________________________________________________
___

self = <登录.test_错误登录.Test_错误密码 object at 0x00000291FE6E4D30>

    @pytest.mark.webtest
    def test_C001003(self):
        print('\n用例C001003')
>       assert 3 == 2
E       assert 3 == 2
E         +3
E         -2

cases\登录\test_错误登录.py:33: AssertionError
____________________________________________________________________ Test_错误的登录.test_UI_0001 ________________________________________________________________
____

self = <登录.test_错误登录_实战.Test_错误的登录 object at 0x00000291FE6BC4F0>

    def test_UI_0001(self):
        print('\n用例UI_0001')
        driver = webdriver.Chrome()
        driver.implicitly_wait(10)

        driver.get("http://127.0.0.1/mgr/index.html")
        # driver.find_element(By.ID, 'username').send_keys('')
        sleep(3)
>       driver.find_element(By.ID, 'password').send_keys('88888888')

cases\登录\test_错误登录_实战.py:19:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
E:\tools\Andconda\lib\site-packages\selenium\webdriver\remote\webdriver.py:1251: in find_element
    return self.execute(Command.FIND_ELEMENT, {
E:\tools\Andconda\lib\site-packages\selenium\webdriver\remote\webdriver.py:430: in execute
    self.error_handler.check_response(response)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = 
response = {'status': 500, 'value': '{"value":{"data":{"text":"HTTP 错误 : 302Found"},"error":"unexpected alert open","message":"un...\n\\tRtlGetAppContainerNamed
ObjectPath [0x77BC7A7E+286]\\n\\tRtlGetAppContainerNamedObjectPath [0x77BC7A4E+238]\\n"}}'}

    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.keys()) == 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]
        if status in ErrorCode.NO_SUCH_ELEMENT:
            exception_class = NoSuchElementException
        elif status in ErrorCode.NO_SUCH_FRAME:
            exception_class = NoSuchFrameException
        elif status in ErrorCode.NO_SUCH_SHADOW_ROOT:
            exception_class = NoSuchShadowRootException
        elif status in ErrorCode.NO_SUCH_WINDOW:
            exception_class = NoSuchWindowException
        elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
            exception_class = StaleElementReferenceException
        elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
            exception_class = ElementNotVisibleException
        elif status in ErrorCode.INVALID_ELEMENT_STATE:
            exception_class = InvalidElementStateException
        elif status in ErrorCode.INVALID_SELECTOR \
                or status in ErrorCode.INVALID_XPATH_SELECTOR \
                or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
            exception_class = InvalidSelectorException
        elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
            exception_class = ElementNotSelectableException
        elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
            exception_class = ElementNotInteractableException
        elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
            exception_class = InvalidCookieDomainException
        elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
            exception_class = UnableToSetCookieException
        elif status in ErrorCode.TIMEOUT:
            exception_class = TimeoutException
        elif status in ErrorCode.SCRIPT_TIMEOUT:
            exception_class = TimeoutException
        elif status in ErrorCode.UNKNOWN_ERROR:
            exception_class = WebDriverException
        elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
            exception_class = UnexpectedAlertPresentException
        elif status in ErrorCode.NO_ALERT_OPEN:
            exception_class = NoAlertPresentException
        elif status in ErrorCode.IME_NOT_AVAILABLE:
            exception_class = ImeNotAvailableException
        elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
            exception_class = ImeActivationFailedException
        elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
            exception_class = MoveTargetOutOfBoundsException
        elif status in ErrorCode.JAVASCRIPT_ERROR:
            exception_class = JavascriptException
        elif status in ErrorCode.SESSION_NOT_CREATED:
            exception_class = SessionNotCreatedException
        elif status in ErrorCode.INVALID_ARGUMENT:
            exception_class = InvalidArgumentException
        elif status in ErrorCode.NO_SUCH_COOKIE:
            exception_class = NoSuchCookieException
        elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:
            exception_class = ScreenshotException
        elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:
            exception_class = ElementClickInterceptedException
        elif status in ErrorCode.INSECURE_CERTIFICATE:
            exception_class = InsecureCertificateException
        elif status in ErrorCode.INVALID_COORDINATES:
            exception_class = InvalidCoordinatesException
        elif status in ErrorCode.INVALID_SESSION_ID:
            exception_class = InvalidSessionIdException
        elif status in ErrorCode.UNKNOWN_METHOD:
            exception_class = UnknownMethodException
        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 = self._value_or_default(frame, 'lineNumber', '')
                        file = self._value_or_default(frame, 'fileName', '')
                        if line:
                            file = "%s:%s" % (file, line)
                        meth = self._value_or_default(frame, 'methodName', '')
                        if 'className' in frame:
                            meth = "%s.%s" % (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
E           selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: HTTP 错误 : 302Found
E           Message: unexpected alert open: {Alert text : HTTP 错误 : 302Found}
E             (Session info: chrome=102.0.5005.63)
E           Stacktrace:

定位问题下来是使用了selenium4.0的语法造成的:

driver.find_element(By.ID, 'password').send_keys('88888888')
修改定位元素的语法为selenium3.0的语法,
driver.find_element_by_id('password').send_keys('88888888')

报错图片:

selenium执行报错:response = {‘status‘: 500, ‘value‘: ‘{“value“:{“data“:{“text“:“HTTP 错误 : 302Foun_第1张图片

 解决问题后的图片

selenium执行报错:response = {‘status‘: 500, ‘value‘: ‘{“value“:{“data“:{“text“:“HTTP 错误 : 302Foun_第2张图片

 

你可能感兴趣的:(pytest框架踩坑,python,selenium,开发语言)