解决这个问题的方法是使用Appium的UiSelector().ResourceIdMatches的Or条件时,正确地使用正则表达式,并且处理NoSuchElementException异常。
以下是一个示例代码,演示了如何使用Or条件和处理NoSuchElementException异常:
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from appium.common.exceptions import NoSuchElementException
import re
desired_caps = {
'platformName': 'Android',
'deviceName': 'device_name',
'appPackage': 'app_package',
'appActivity': 'app_activity'
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
try:
# 使用Or条件和正则表达式查找元素
element = driver.find_element(MobileBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceIdMatches(".*text_view1|.*text_view2")')
# 处理元素找到后的操作
element.click()
element.send_keys("Hello Appium!")
except NoSuchElementException:
# 处理元素未找到的情况
print("Element not found.")
finally:
driver.quit()
在上面的示例代码中,我们使用了正则表达式 ".*text_view1|.*text_view2"
来匹配 resourceId,其中 |
表示逻辑或。这样可以匹配 resourceId 为 text_view1
或 text_view2
的元素。
在 try 块中,我们在执行 driver.find_element
时捕获了 NoSuchElementException 异常。如果元素未找到,就会跳到 except 块中处理该异常。
请注意,这只是一个示例代码,具体的 resourceId 和其他条件需要根据你的实际情况进行修改。