一、前置说明
Appium升级后不再支持使用name定位,我们可以使用UiSelector文本定位解决这个问题,而且UiSelector支持更加灵活的text定位方式。
二、代码实现
def find_elements_by_text(self, value, platform='android', rule='full'): CommonChecker.check_item_in_list(platform, ['android', 'ios'], field_name='platform') CommonChecker.check_item_in_list(rule, ['full', 'partial', 'startswith', 'regex'], field_name='rule') selector_method = { 'full': 'text', 'partial': 'textContains', 'startswith': 'textStartsWith', 'regex': 'textMatches' } statement = f'new UiSelector().{selector_method[rule]}("{value}")' if platform == 'android': return self.find_elements(AppiumBy.ANDROID_UIAUTOMATOR, statement) elif platform == 'ios': return self.find_elements(AppiumBy.IOS_UIAUTOMATION, statement) else: raise ValueError(f"Unsupported platform: {platform}") def find_element_by_text(self, value, platform='android', rule='full', index=0) -> WebElement: elements = self.find_elements_by_text(value, platform, rule) if not elements: raise NoSuchElementException(f"No elements found for value: {value}, platform: {platform}, rule: {rule}") return CommonChecker.check_and_get_element_by_index(elements, index, field_name='index')
三、Demo验证
测试代码:
def test_find_element_by_text(): from driver.appium.driver import WebDriver appium_server_url = 'http://localhost:4723' capabilities = { "platformName": "Android", "automationName": "uiautomator2", "deviceName": "127.0.0.1:62001", "app": "D:\\resources\\imooc.apk", } driver = WebDriver(command_executor=appium_server_url, capabilities=capabilities) time.sleep(2) driver.swipe_to('left', num=2) time.sleep(2) driver.find_element('id', 'cn.com.open.mooc:id/viewpager').click() time.sleep(3) ele = driver.find_element_by_text(value='注册', rule='full') assert ele.text == '注册' ele = driver.find_element_by_text(value='去登录', rule='partial') assert ele.text == '已有慕课网账号? 去登录' ele = driver.find_element_by_text(value='注册慕课网账号', rule='startswith') assert ele.text == '注册慕课网账号' ele = driver.find_element_by_text(value='^注册.*账号$', rule='regex') assert ele.text == '注册慕课网账号'
控制台输出结果:
============================= test session starts ============================= collecting ... collected 1 item test_appium.py::test_find_element_by_text PASSED [100%] ============================= 1 passed in 26.68s ==============================