AppiumLibrary库定位元素


AppiumLibrary库定位元素

AppiumLibrary中所有需要在页面上查找元素的关键字都带有一个参数,即locatorwebelement.locatorlocator是一个字符串,它描述如何使用指定不同定位策略的语法来定位元素。webelement是一个变量,其中包含一个WebElement实例,该实例是元素的表示形式。

使用定位器

默认情况下,提供定位符后,它会与特定元素类型的关键属性进行匹配。对于iOS和Android,键属性是所有元素的id,仅使用id即可轻松定位元素。例如:

Click Element    id=my_element

AppiumLibrary 1.4中的新增功能,不需要指定idxpath,但是xpath应该以//开头,否则只需使用xpath定位器,如下所述。

Click Element    my_element
Wait Until Page Contains Element    //*[@type="android.widget.EditText"]

Appium还支持某些 Mobile JSON Wire Protocol定位器策略。也可以通过指定带有定位符前缀的查找策略来指定AppiumLibrary查找元素所采用的方法。支持的策略是:

Strategy Example Description Note
identifier Click Element | identifier=my_element Matches by @id attribute
id Click Element | id=my_element Matches by @resource-id attribute
accessibility_id Click Element | accessibility_id=button3 Accessibility options utilize.
xpath Click Element | xpath=//UIATableView/UIATableCell/UIAButton Matches with arbitrary XPath
class Click Element | class=UIAPickerWheel Matches by class
android Click Element | android=UiSelector().description('Apps') Matches by Android UI Automator
ios Click Element | ios=.buttons().withName('Apps') Matches by iOS UI Automation
nsp Click Element | nsp=name=="login" Matches by iOSNsPredicate Check PR: #196
css Click Element | css=.green_button Matches by css in webview
name Click Element | name=my_element Matches by @name attribute Only valid for Selendroid

使用webelements

从AppiumLibrary的1.4版开始,可以传递一个包含WebElement而不是字符串定位符的参数。要获取WebElement,请使用新的Get WebElementsGet WebElement关键字。

@{elements}    Get Webelements    class=UIAButton
Click Element    @{elements}[2]

实例

*** Settings ***

Library    AppiumLibrary    

*** Test Cases ***
case01
    log    case01
    Open Application    http://127.0.0.1:4723/wd/hub   platformName=Android  
    ...  platformVersion=9.0   udid=emulator-5554   deviceName=Pixel 2 API 28  
    ...  appPackage=com.android.calculator2   appActivity=com.android.calculator2.Calculator

    # Sleep    3

    Click Element    id=com.android.calculator2:id/digit_1    
    Click Element    id=com.android.calculator2:id/op_add
    Click Element    id=com.android.calculator2:id/digit_2

    Click Element    id=com.android.calculator2:id/eq