Python+Appium+Android的基本使用方法

Appium连接设备的方法

运行Appium

image-20200901110220914

配置参数

测试相机应用只需要改<deviceName>设备序列号即可。

获取<deviceName>设备序列号的方法:

image-20200901085235658

​ 若测试其它应用需要更改<appPackage><appActivity>

​ 获取<appPackage><appActivity>设备序列号的方法:

image-20200901091542586

from appium import webdriver
deviceName = 'f65c397eb691'     # 指定序列号
 
# 配置设备参数
desired_caps = {
    'platformName': 'Android',           # 平台名称
    'platformVersion': '10',             # 系统版本号
    'deviceName': deviceName,            # 设备名称。可以使用'设置->关于手机->设备名称',也可以使用序列号。
    'appPackage': 'com.gree.camera',     # apk的包名
    'appActivity': '.activity.CameraActivity',  # activity 名称
    'automationName': 'uiautomator1',    # 自动化服务名称
    'udid': deviceName,                  # 设备序列号
    "noReset": "true",                   # 是否重置
    'newCommandTimeout': '1800',         # 设置新命令最长等待时间
}
 
# 连接设备
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
driver.implicitly_wait(8)   # 指令最长等待时间,即8秒内找不到元素则报错

UI元素查看器

uiautomatorviewer

可使用Android SDK原生的uiautomatorviewer也可以使用二次开发的uiautomatorviewer。

下图为二次开发的uiautomatorviewer,好处在于能生成脚本代码。

image-20200901104246025

Appium

启动检查器会话

image-20200901110551828

启动会话

image-20200901111101814

录制操作/查看元素

image-20200901111453317

元素定位

定位方法 取值 举例 备注
通过id定位 resource-id driver.find_element_by_id("<resource-id>")
通过text定位 text driver.find_element_by_xpath("//*[@text='<text>']")
通过text定位(Uiautomator) text driver.find_elements_by_android_uiautomator('new UiSelector().text("<text>")') 返回列表
通过description定位(Uiautomator) description/content-desc driver.find_elements_by_android_uiautomator('new UiSelector().description("<description>")') 返回列表
通过class_name定位 class driver.find_element_by_class_name("<class>")
通过xpath定位 xpath driver.find_element_by_xpath("<xpath>")

Appium执行shell命令

前置条件:需要开启Appium放松安全性,上文"运行Appium"中有说到。

def adb_shell(self, command):
    """执行adb shell命令,需要appium高级设置-放松安全性"""
    try:
        result = self.driver.execute_script('mobile: shell', {'command': command, 'includeStderr': True})
        return result['stdout']
    except WebDriverException as e:
        return str(e).split('StdErr:')[-1].strip()

使用方法:

adb_shell('ls /sdcard/')
# 等同于adb shell ls /sdcard/
posted @ 2020-09-02 14:23  嗷呜恐龙  阅读(333)  评论(0编辑  收藏  举报