appium定位

appium的常用操作以及元素定位的简单介绍

appium常用操作

锁屏

1
driver.lock(5)

切换应用至后台

1
2
3
driver.background_app(5)  # 置于后台,持续5秒
driver.background_app(-1) # 持续置于后台
driver.background_app({'timeout': None}) # 持续置于后台

收起键盘

1
driver.hide_keyboard()

启动Activity

1
driver.start_activity('com.example.android.apis', '.Foo')

检测应用是否被安装

1
driver.is_app_installed('com.example.android.apis')

安装应用

1
driver.install_app('path/to/my.apk')

卸载应用

1
driver.remove_app('com.example.android.apis')

模拟设备摇一摇

1
driver.shake()

关闭应用

1
driver.close_app()

启动应用

使用前提是desired capabilities 设置了 autoLaunch=false 关键字

1
driver.launch_app()

操作上下文(Contexts)

获取所有

1
driver.contexts

获取当前

1
driver.current_context

切换至默认

1
driver.switch_to.context(None)

按键事件

1
driver.keyevent(176)

具体键值

点击操作/多点触控操作

1
2
action = TouchAction(driver)
action.press(element=el, x=10, y=10).release().perform()

滑动屏幕

1
driver.swipe(start_x=75, start_y=500, end_x=75, end_y=0, duration=800)

从设备拉去文件

1
driver.pull_file('Library/AddressBook/AddressBook.sqlitedb')

推送文件到设备

1
2
3
data = "some data for the file"
path = "/data/local/tmp/file.txt"
driver.push_file(path, data.encode('base64'))

appium元素定位

使用id,class等和selenium基本没差别的定位就不介绍了,主要介绍appium独有uiautomator UiSelector

页面class和id等都不能唯一确定元素,但是元素有text属性时,可以使用以下进行定位:

1
2
3
4
driver.find_element_by_android_uiautomator('new UiSelector().text("Custom View")').click()         #text
driver.find_element_by_android_uiautomator('new UiSelector().textContains("View")').click() #textContains
driver.find_element_by_android_uiautomator('new UiSelector().textStartsWith("Custom")').click() #textStartsWith
driver.find_element_by_android_uiautomator('new UiSelector().textMatches("^Custom.*")').click() #textMatches

也可以加上class属性:

1
2
driver.find_element_by_android_uiautomator('new UiSelector().className("android.widget.TextView").text("Custom View")').click()     #className
driver.find_element_by_android_uiautomator('new UiSelector().classNameMatches(".*TextView$").text("Custom View")').click() #classNameMatches

多条件精准定位

1
driver.find_element_by_android_uiautomator('new UiSelector().className("android.widget.EditText").resourceId("com.anmav.cashierdesk:id/etToPayPrice")')

操作坐标

appium在进行元素定位时,定位不到唯一标志的元素,可以获取元素的坐标,使用坐标进行操作

appium以及uiautomatorviewer都可以很容易获取到坐标

appium操作坐标

1
driver.tap([(100, 20), (100, 60), (100, 100)], 500)

三个坐标表示模拟三根手指,只需要一个手指,改成一个坐标即可,500表示持续时间500ms

或者使用adb命令也可实现同样效果:

1
os.popen("adb shell input tap " + str(100) + " " + str(20))

参考文章

appium 基础之键盘处理
appium-bindings

文章目录
  1. appium常用操作
    1. 锁屏
    2. 切换应用至后台
    3. 收起键盘
    4. 启动Activity
    5. 检测应用是否被安装
    6. 安装应用
    7. 卸载应用
    8. 模拟设备摇一摇
    9. 关闭应用
    10. 启动应用
    11. 操作上下文(Contexts)
      1. 获取所有
      2. 获取当前
      3. 切换至默认
    12. 按键事件
    13. 点击操作/多点触控操作
    14. 滑动屏幕
    15. 从设备拉去文件
    16. 推送文件到设备
  2. appium元素定位
  3. 操作坐标
  4. 参考文章
|