Skip to main content
 首页 » 编程设计

python之NoSuchElementException 与 uiautomator2

2024年12月31日25zhenyulu

我正在尝试在 Sauce Labs 上运行我的 Python 代码,它在未设置 automationName 功能的情况下工作正常(根据 http://appium.io/docs/en/writing-running-appium/caps/ 默认为 Appium) .但是,当我将此功能设置为 UiAutomator2 时,它会在 element_some_text = self.driver.find_element_by_xpath("//android.widget.TextView[@text='Some Text ']"):

NoSuchElementException:消息:使用给定的搜索参数无法在页面上找到元素。

这是我的代码:

import lemoncheesecake.api as lcc 
from appium import webdriver 
 
 
@lcc.suite("My test suite") 
class my_test_suite: 
    caps = {} 
    driver = None 
 
    def setup_suite(self): 
        self.caps['appiumVersion'] = "1.8.1" 
        self.caps['deviceName'] = "Android GoogleAPI Emulator" 
        self.caps['deviceOrientation'] = "portrait" 
        self.caps['platformVersion'] = "7.1" 
        self.caps['platformName'] = "Android" 
        self.caps['automationName'] = 'uiautomator2' 
        self.caps['autoGrantPermissions'] = True 
        self.caps['app'] = 'https://somesite.com/storage/my_app.apk' 
        self.caps['appPackage'] = 'com.xxx.abc.my_app' 
        self.driver = webdriver.Remote( 
            'http://username:passkey@ondemand.saucelabs.com:80/wd/hub', self.caps) 
 
    @lcc.test("My app test") 
    def verify_app_launch(self): 
        self.driver.implicitly_wait(10) 
        element_some_text = self.driver.find_element_by_xpath("//android.widget.TextView[@text='Some Text']") 
        element_some_text.click() 
 
    def teardown_suite(self): 
        self.driver.quit() 

请您参考如下方法:

在所需的 Some Text 元素出现之前使用显式等待元素(定义如下)的不可见性解决了这个问题。 奇怪的是,在默认automationName 的情况下不需要这种明确的等待。

wait = WebDriverWait(self.driver, 20) 
wait.until(EC.invisibility_of_element_located((By.ID, "com.xxx.abc.my_app:id/prior_element"))) 

PS:虽然我知道这个答案可能会遭到一些反对,但我坚信这是 UiAutomator2 引擎的一种奇怪行为。