Appium中是否可以通过ID查找元素?

22

以下链接提到我们可以通过 id 查找元素... 但是我无法找到它。

https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/finding-elements.md

通过“名称”查找(即元素的文本、标签或开发人员生成的 ID,也称为 'accessibilityIdentifier')

我尝试了以下代码:

WebElement el = driver.findElement(By.name("txtLogin"));

其中txtLogin是登录按钮的ID。

它会抛出以下异常:

org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters. (WARNING: The server did not provide any stacktrace information)

请问有哪些方法可以在Appium中找到元素?

6个回答

24
你可以按照以下方式使用元素ID:-
软件包名称:com.example.testap 元素ID:txtLogin 编写以下代码 -
 driver.findElement(By.id("com.example.testapp:id/txtLogin")).sendKeys("abc");

这仅适用于Android版本>=18吗? - Shobhit Puri
1
如果您的按钮属于另一个应用程序,且该应用程序未包含在期望功能中,则应使用其包名称和ID。因此,在您的情况下,driver.findElement(By.id("txtLogin")).sendKeys("abc"); 将起作用。 - Chandrashekhar Swami

6

这里是使用Appium定位元素最常用的Java代码示例

//Find element by id and enter Hello in Text box.

    driver.findElementById("edit_name").sendKeys("Hello");
    //Find element by class name and enter Hello in Text box.

     driver.findElementByClassName("com.android.EditText").sendKeys("Hello");
    //Find element by xpath and enter Hello in Text box.

    driver.findElementByXPath("//cass[@value='Enter Name']").sendKeys("Hello");
    //Find element by link text and enter Hello in Text box.

    driver.findElementByLinkText("Enter Name").sendKeys("Hello");

如果你想学习更多在Appium中查找本地和Webview元素的方法,请点击这里


5
你也可以使用 Xpath 按 id 查找元素,例如在此处: enter image description here 该元素具有 class="android.widget.Button"id="digit5",因此你可以按如下方式查找: xpath("//android.widget.Button[contains(@resource-id,'digit5')]") Xpath 最有用的地方在于当你需要应用 多个 条件时,比如: xpath("//android.widget.Button[contains(@resource-id,'digit5') and @text='5']") 更多详细信息,请访问以下网站: http://www.software-testing-tutorials-automation.com/2015/10/ui-automator-viewer-get-android-app.html

1

在Android API级别低于18的情况下,无法通过id获取元素。您可以在uiautomatorviewer中检查id是否存在。如果不存在,则可以获取所有类型为EditView的元素,并迭代它以找到正确的字段来发送文本。

使用以下方式 -

public List<WebElement> getWebElementList(By by) {

        return driver.findElements(by);
    }

public void details() throws InterruptedException{

        List<WebElement> weList = null;
        weList = getWebElementList(By.tagName("android.widget.EditView"));
        for (WebElement we : weList) {
            if(we.getText().toLowerCase().contains("login")){
                we.sendkeys("Hello");
            }
        }           
    }

希望这有所帮助。

1
你可以使用android的来查找元素ID。 只需前往SDK工具文件夹D:\ Android \ android-sdk \ tools,您就可以找到uiautomatorviewer。 打开它并拍摄您的活动屏幕截图,并查找任何元素的ID,类和包。

enter image description here


1
资源 ID 是该 ID。 - Tarun

1
在 Appium 1.0 及以上版本中,findElementByTagName 已被弃用。
您需要使用带有限定类名的 findElementByClassName 替代。 以下是 Android 中 EditTextField 和 Button 的代码:

findElements(By.className("android.widget.EditText"));

findElements(By.className("android.widget.Button"));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接