测试人社区

企业微信实战----NoSuchElementException错误---请帮忙查看原因--运行的是test-addcontact这部分的代码

代码如下:
#联系人用例
import yaml
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.wait import WebDriverWait
import pytest
import time

with open(‘datas/contact.yml’,‘r’,encoding=‘utf-8’) as f:
addcontactdatas = yaml.safe_load(f)

class TestContact:

def setup_class(self):
    caps = {}
    caps["platformName"] = "android"
    caps["deviceName"] = "127.0.0.1:7555"
    caps["appPackage"] = "com.tencent.wework"
    caps["appActivity"] = ".launch.LaunchSplashActivity"
    caps["noReset"] = "true"
    caps['skipServerInstallation'] = 'true'  # 跳过 uiautomator2 server的安装
    caps['skipDeviceInitialization'] = 'true'  # 跳过设备初始化
    #caps['dontStopAppOnReset'] = 'true'  # 启动之前不停止app
    caps['settings[waitForIdleTimeout]'] = 0
    # 与sever建立连接,初始化一个driver 创建session,返回一个session
    self.driver = webdriver.Remote('http://localhost:4723/wd/hub', caps)
    self.driver.implicitly_wait(10)


def teardown_class(self):
    self.driver.quit()

@pytest.mark.parametrize('name,gender,phonenumber',
                         addcontactdatas,)
def test_addcontact(self,name,gender,phonenumber):
    '''
           添加联系人
           添加联系人用例设计
           1.打开应用
           2.点击通讯录
           3.点击添加成员
           4.手动输入添加
           5.输入用户名性别手机号
           6.点击保存
           7.验证添加成功
           '''
    # name = "霍格沃兹1"
    # gender = "女"
    # phonenumber = "13552896543"

    self.driver.find_element(MobileBy.XPATH, "//android.widget.TextView[@text='通讯录']").click()
    self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR,
                             'new UiScrollable'
                             '(new UiSelector().'
                             'scrollable(true).'
                             'instance(0)).'
                             'scrollIntoView('
                             'new UiSelector().'
                             'text("添加成员").instance(0));').click()
    self.driver.find_element(MobileBy.XPATH,
                             "//android.widget.TextView[@text='手动输入添加']").click()
    # 设置姓名

    self.driver.find_element(MobileBy.XPATH,
                             "//*[contains(@text,'姓名')]/../*[@class='android.widget.EditText']").send_keys(name)

    # 设置性别
    self.driver.find_element(MobileBy.XPATH,
                             "//*[contains(@text,'性别')]/..//*[@text='男']").click()
    if gender == '男':
        time.sleep(2)
        self.driver.find_element(MobileBy.XPATH, "//*[@text='男']").click()
    else:
        time.sleep(2)
        self.driver.find_element(MobileBy.XPATH, "//*[@text='女']").click()
    # 设置手机号
    self.driver.find_element(MobileBy.XPATH, "//*[@text='手机号']").send_keys(phonenumber)
    # 点击保存
    self.driver.find_element(MobileBy.ID, "com.tencent.wework:id/hvk").click()
    # 验证成功 Toast
    # self.driver.find_element(MobileBy.XPATH,"//*[@class='android.widget.Toast']").text
    # element = WebDriverWait(self.driver, 10).until(
    #     lambda x: x.find_element(MobileBy.XPATH, "//*[@class='android.widget.Toast']"))

    time.sleep(5)
    # result = element.text
    # assert '成功' in result
    #self.driver.back()
    # 验证成功

def test_delcontact(self):
    '''
    删除联系人
    '''
    name = "霍格沃兹name3"
    self.driver.find_element(MobileBy.XPATH,
                             "//android.widget.TextView[@text='通讯录']").click()
    #点击搜索框
    self.driver.find_element(MobileBy.ID,
                            "com.tencent.wework:id/hvn").click()
    #输入联系人姓名
    self.driver.find_element(MobileBy.ID,
                             "com.tencent.wework:id/hv3").send_keys(name)
    #获取联系人列表
    elelist = self.driver.find_elements(MobileBy.XPATH,"//*[@text='{name}']")
    #判断搜索出的列表长度
    if len(elelist) < 2:
        print("没有这个联系人")
        return
    #存在联系人点击第一个
    elelist[1].click()
    self.driver.find_element(MobileBy.ID,"com.tencent.wework:id/hvd").click()
    #点击编辑成员
    self.driver.find_element(MobileBy.XPATH, "//*[@text='编辑成员']").click()
    #滚动查找删除成员并点击
    self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR,
                             'new UiScrollable'
                             '(new UiSelector().'
                             'scrollable(true).'
                             'instance(0)).'
                             'scrollIntoView('
                             'new UiSelector().'
                             'text("删除成员").instance(0));').click()
    #确定删除
    self.driver.find_element(MobileBy.XPATH, "//*[@text='确定']").click()
    time.sleep(2)
    #验证删除成功
    elelist_after = self.driver.find_elements(MobileBy.XPATH, "//*[@text='{name}']")

    assert len(elelist) - len(elelist) == 1

报错信息如下:
FAILED
testing\appium\test_contact1.py:32 (TestContact.test_addcontact[\u970d\u683c\u6c83\u5179name2-\u5973-13552896545])
self = <test_contact1.TestContact object at 0x00000213BD07ED90>
name = ‘霍格沃兹name2’, gender = ‘女’, phonenumber = ‘13552896545’

@pytest.mark.parametrize('name,gender,phonenumber',
                         addcontactdatas,)
def test_addcontact(self,name,gender,phonenumber):
    '''
           添加联系人
           添加联系人用例设计
           1.打开应用
           2.点击通讯录
           3.点击添加成员
           4.手动输入添加
           5.输入用户名性别手机号
           6.点击保存
           7.验证添加成功
           '''
    # name = "霍格沃兹1"
    # gender = "女"
    # phonenumber = "13552896543"
  self.driver.find_element(MobileBy.XPATH, "//android.widget.TextView[@text='通讯录']").click()

test_contact1.py:51:


C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\appium\webdriver\webdriver.py:279: in find_element
return self.execute(RemoteCommand.FIND_ELEMENT, {
C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\remote\webdriver.py:321: in execute
self.error_handler.check_response(response)
C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\appium\webdriver\errorhandler.py:31: in check_response
raise wde
C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\appium\webdriver\errorhandler.py:26: in check_response
super().check_response(response)


self = <appium.webdriver.errorhandler.MobileErrorHandler object at 0x00000213BD0A8700>
response = {‘status’: 404, ‘value’: ‘{“value”:{“error”:“no such element”,“message”:“An element could not be located on the page u…11)\n at runMicrotasks ()\n at processTicksAndRejections (internal/process/task_queues.js:85:5)”}}’}

def check_response(self, response):
    """
    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 status is None or status == ErrorCode.SUCCESS:
        return
    value = None
    message = response.get("message", "")
    screen = response.get("screen", "")
    stacktrace = None
    if isinstance(status, int):
        value_json = response.get('value', None)
        if value_json and isinstance(value_json, basestring):
            import json
            try:
                value = json.loads(value_json)
                if len(value.keys()) == 1:
                    value = value['value']
                status = value.get('error', None)
                if status is None:
                    status = value["status"]
                    message = value["value"]
                    if not isinstance(message, basestring):
                        value = message
                        message = message.get('message')
                else:
                    message = value.get('message', None)
            except ValueError:
                pass

    exception_class = ErrorInResponseException
    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_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 value == '' or value is None:
        value = response['value']
    if isinstance(value, basestring):
        if exception_class == ErrorInResponseException:
            raise exception_class(response, value)
        raise exception_class(value)
    if message == "" and 'message' in value:
        message = value['message']

    screen = None
    if 'screen' in value:
        screen = value['screen']

    stacktrace = None
    if 'stackTrace' in value and value['stackTrace']:
        stacktrace = []
        try:
            for frame in value['stackTrace']:
                line = self._value_or_default(frame, 'lineNumber', '')
                file = self._value_or_default(frame, 'fileName', '<anonymous>')
                if line:
                    file = "%s:%s" % (file, line)
                meth = self._value_or_default(frame, 'methodName', '<anonymous>')
                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 == ErrorInResponseException:
        raise exception_class(response, message)
    elif 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)
  raise exception_class(message, screen, stacktrace)

E selenium.common.exceptions.NoSuchElementException: Message: An element could not be located on the page using the given search parameters.

C:\Users\Administrator\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\remote\errorhandler.py:242: NoSuchElementException

没找到元素,检查下当前页面元素是否存在

第一个联系人添加成功了。。。停留在添加添加成员这个页面上。。。。

这里被注释了,没有返回上一页,所以在当前页面找不到通讯录

已经解决了 多谢~