无法使用 Appium 通过 XPATH 找到元素/Python

Not able to find element by XPATH using Appium / Python

我正在自动化一个流程,该流程包括从 Xamarin ListView 产品列表中点击产品名称以进入产品详细信息页面。

我已经在我的 ListView 中设置了:

AutomationProperties.IsInAccessibleTree="false"

并且在产品名称标签中:

AutomationId="ProductName"

有趣的是,当使用 Appium Desktop UI 检查工具时,我可以看到 XPATH,如果我对它进行记录,它确实有效,我得到了这个脚本:

MobileElement el1 = (MobileElement) driver.findElementByXPath("(//XCUIElementTypeStaticText[@name=\"ProductName\"])[1]");
el1.click();

为此,我知道 XPATH 存在并且对 Appium 可见。它在检查工具中有效。

现在,当我将其翻译成 Python 时,出了点问题:

el1 = self.driver.find_element_by_xpath("(//XCUIElementTypeStaticText[@name=\"ProductName\"])[1]")

我收到此错误消息:

el = self.driver.find_element_by_xpath(element_query) 文件“/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py”,第 393 行,在 find_element_by_xpath 中 return self.find_element(by=By.XPATH, value=xpath) 文件“/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py”,第 966 行,在 find_element 中 'value': 值})['value'] 文件“/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py”,第 320 行,在执行中 self.error_handler.check_response(回应) 文件“/Users/joseclua/Library/Python/3.7/lib/python/site-packages/appium/webdriver/errorhandler.py”,第 29 行,在 check_response 中 提高 wde 文件“/Users/joseclua/Library/Python/3.7/lib/python/site-packages/appium/webdriver/errorhandler.py”,第 24 行,在 check_response 中 超级(MobileErrorHandler,自我)。check_response(响应) 文件“/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py”,第 242 行,在 check_response 中 提高 exception_class(消息、屏幕、堆栈跟踪) selenium.common.exceptions.NoSuchElementException:消息:使用给定的搜索参数无法在页面上找到元素。

Using Xpath is not recommended in appium

您可以使用 cont-desc、id、resource-id 来实现自动化。由于您使用的是xamarin项目,您可以在项目中添加自动化代码。

然后您可以在检查应用程序时看到 cont-desc。然后你可以使用元素作为:

el = self.driver.find_elements_by_accessibility_id('ProductName');

感谢 Suban 的洞察力,我能够利用列表元素并避免使用不推荐的 XPath。

这是我现在在 iOS 上使用的代码。我仍然需要在 Android.

中进行测试
def list_item_tap(self, el_name):
    print("list_item_tap {0}", el_name)
    li = self.driver.find_elements_by_accessibility_id(el_name)
    print("list items: {0}", len(li))
    if len(li) > 0:
        el = li[0]
        time.sleep(2)
        el.click()

没有休眠点击好像失败了

谢谢苏班

您可以使用其他方法查找元素,如 id、UIAutomator、classname 等

用于 id *driver.findElementById("id").click();

对于 UIAutomator 使用 driver.findElementByAndroidUIAutomator("text(\"Text\")").click();

对于 Classname 使用 driver.findElementByClassName("Class Name").click();

希望这对您有所帮助。

我一般建议在触发点击元素之前检查元素的可见性一段时间更安全。像这样:

    elem_to_find = WebDriverWait(
        driver, 5).until(
            EC.visibility_of_element_located(
                ('xpath or id or class of the element, considering xpath in this case', MobileBy.XPATH)))
    elem_to_find.click()