appium的css定位符支持

appium在1.19.0版本之后新增了css定位符,是个重大的改变。记录下

支持单一属性的定位

  • 属性定义
    • *[#id]
    • *[description="Some description"]
    • *[text="Some description"]
  • 类定位
    • android.widget.EditText
    • android.widget.TextView[description="Some description"]

原文

The CSS selector is going unused in all Appium Drivers :cry: . Why not put it to use?

This PR adds support for a native CSS selector strategy. Instead of using CSS to select HTML elements, it parses CSS selectors and translate the selector to a native -android uiautomator selector.

Example

android.widget.TextView[description="Some description"]

translates to

new UiSelector().className("android.widget.TextView").description("Some description")

ie:

elementByCss('android.widget.TextView[description="Some description"]')

does the same thing as

elementBy('-android uiautomator', 'new UiSelector().className("android.widget.TextView").description("Some description")')

many more examples in css-converter-specs.js and by-css-e2e-specs.js

Versatile

This selector can be used to replace every other selector:

  • find by id:
    elementsById("someResourceID")
    elementsByCss("#someResourceID")
  • find by class name:
    elementsByClassName("android.widget.TextView")
    elementsByCss("android.widget.TextView")
  • find by accessibility id:
    elementsByAccessibilityId("Some Content Description")
    elementsByCss('*[description="Some Content Description"]')
  • find by xpath:
    elementsByXpath("//android.widget.TextView[@description='Accessibility']")elementsByCss("android.widget.TextView[description='Accessibility']")

Performance

Unlike Xpath, this selector doesn’t require a document to be generated that the selector is applied to. It just parses the CSS selector and translates it to an analagous UiAutomator selector.

How is it done?

  • css is parsed by css-converter.js which uses the css-selector-parser - npm library
  • the CSS object is parsed and converted to a UiSelector expression that is passed to UiAutomator2 Server as -android uiautomator selector

How is it different from CSS selectors being applied to HTML?

  • Throws exceptions if unsupported attributes are given. This is so that it’s more helpful for users so they can see when they’re using a bad attribute
  • The descendant operators (>, ~, …) are unsupported.
  • Class names:
    • For HTML CSS selectors, a selector like p.classOne.classTwo means that it’s matching an HTML <p> element that has classOne and classTwo as class attributes (order doesn’t matter).
    • For this UiAutomator2 CSS selector, a selector like android.widget.TextView means that it’s matching a widget with the fully qualified Java class name android.widget.TextView