元素选择器介绍

概述

元素选择器基于android屏幕XML dump来分析每个屏幕元素,是整套自动化控制体系的核心所在,通过元素选择器来操作,系统会自动适配各种不同屏幕的分辨率,无需担心不同手机不同分辨率的差异化。

例子代码

  -- 点击元素ID为abc的按钮.
  selector({resourceId='abc'}).click()
  -- 显示元素ID为abc的元素信息 
  print(selector({resourceId='abc'}).info())

选择器

选择器用于选择当前手机屏幕上的控件(如按钮,图片,文本框等等)

# 下面代码选择了文本为'登录',且classname为TextView的控件
登录按钮 = selector({text='登录', className='android.widget.TextView'})

选择器支持一下参数,你也可以安卓官方文档了解选择器详细信息 UiSelector java doc .

  • text, textContains, textMatches, textStartsWith
  • className, classNameMatches
  • description, descriptionContains, descriptionMatches, descriptionStartsWith
  • checkable, checked, clickable, longClickable
  • scrollable, enabled,focusable, focused, selected
  • packageName, packageNameMatches
  • resourceId, resourceIdMatches
  • index, instance

多个控件处理

  • 多个控件处理

    很多时候屏幕上出现多个相同的空间,比如:两个登录按钮 这种情况下,你可以使用 "instance" 在选择器中表示第几个控件,代码如下:

    登录按钮 = {text="登录", instance=0}  # 这段代码意思是选择第一个带有"登录"文字的空间
    

    对于多个控件,我们还提供以下方法供你使用.

    # 获得当前屏幕上面的"登录"文本空间的出现次数
    selector({text="登录"}).count()
    
    # 获得控件根据实例索引(index)
    selector({text="登录", instance=0})
    selector({text="登录", instance=1})
    

获得控件状态和控件信息

  • 检查控件是否存在

    -- 如果存在则返回true,否则返回false
    selector({text="登录"}).exists() 
    -- 等同于
    exists({text="登录"})
    
  • 获得控件的详细信息

    selector({text=u"登录"}).info()
    --等同于
    info({text=u"登录"})
    

    下面是获取控件信息的结果举例:

    { u'contentDescription': u'',
      u'checked': False,
      u'scrollable': False,
      u'text': u'Settings',
      u'packageName': u'com.android.launcher',
      u'selected': False,
      u'enabled': True,
      u'bounds': {u'top': 385,
                  u'right': 360,
                  u'bottom': 585,
                  u'left': 200},
      u'className': u'android.widget.TextView',
      u'focused': False,
      u'focusable': True,
      u'clickable': True,
      u'chileCount': 0,
      u'longClickable': True,
      u'visibleBounds': {u'top': 385,
                         u'right': 360,
                         u'bottom': 585,
                         u'left': 200},
      u'checkable': False
    }
    
  • 清空文本框内容
    --清空用户名输入框
    selector({text="用户名"}).clear
    

在目标控件上面执行点击动作

  • 在目标控件上执行”点击”动作

    -- 点击目标控件的中间位置
    selector({text="登录"}).click()
    -- 也可以简写为:
    tap({text="登录"})
    
  • 在目标控件执行”长按“操作

    -- 长按目标控件的中间位置
    selector({text="登录"}).touch()
    -- 等同于
    touch({text="登录"})
    

查找所有元素

  • 循环所有属性一致的元素
      nodes = selector({className='android.widget.ImageView'}).findAll()
      --显示一共多少个
      print(#nodes)
      for i, v in ipairs(nodes) do
          print(v)
          --元素信息
          print(info(v))
          --等同于上面的
          print(selector(v).info())
      end
    
powered by GitbookFile Modify: 2021-03-27 23:14:19

results matching ""

    No results matching ""