Appium自动化浅尝

上一话我们介绍了基本的安装以及环境搭建,下面来用一个Appium+Python自动化操作哔哩哔哩App搜索并关注RNG官方账号的实例作为我们的自动化初尝。

模拟器准备

下载好哔哩哔哩apk,安装在夜神模拟器中,或者在模拟器的商店安装也行。记得进入设置-关于平板电脑-版本号,连续点击五次版本号,进入开发者模式,然后再打开usb调试。这样电脑端就可以识别到模拟器了。

Appium准备

开启Appium Server GUI:
Appium自动化浅尝_第1张图片

Host填写127.0.0.1,Port填写:4723,然后开启服务器。

Appium自动化浅尝_第2张图片

Appium Inspector准备

接下来是利用Appium Inspector查看元素。
Appium自动化浅尝_第3张图片

如上图,Remote path填写/wd/hub,然后就是填写一些对应的参数。

其中appPackageappActivity,我们可以通过以下方式来获取:

打开目标应用,然后在终端输

adb shell dumpsys activity recents | find "intent={"

在输出的结果中就可以找到以上的两个信息,如哔哩哔哩的:

intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=tv.danmaku.bili/.MainActivityV2}
    intent={act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000100 cmp=com.android.launcher3/.launcher3.Launcher}
    intent={flg=0x10804000 cmp=com.android.systemui/.recents.RecentsActivity}
    intent={act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10800100 cmp=com.android.settings/.FallbackHome}

tv.danmaku.bili就是appPackage.MainActivityV2就是appActivity

Capabilities填写完成后,可以另存为,下次方便使用。接着打开模拟器中的应用然后点击Inspector的开始会话,就会有如下界面:

Appium自动化浅尝_第4张图片

这样就可以开始定位App中的元素了,如果应用切换了界面,就在Inspector中刷新一下。

下面是完整的代码:

from appium import webdriver
from selenium.webdriver.common.by import By
from appium.webdriver.extensions.android.nativekey import AndroidKey
"""

@date:  20220409

@target:    自动操作哔哩哔哩App搜索RNG,并关注RNG官方账号

@author:    Hincy

"""

desired_caps = {
    'platformName':'Android',           # 被测手机为安卓
    'platformVersion':'7.1.2',          # 手机安卓版本
    'deviceName':'HUAWEI',              # 设备名,安卓手机可以随便填写
    'appPackage':'tv.danmaku.bili',     # 启动App,Package名称
    'appActivity':'.MainActivityV2',    # 启动Activity名称
    'unicodeKeyboard':True,             # 使用自带输入法,输入中文时填写True
    'resetKeyboard':True,               # 执行完程序恢复原来输入法
    'noReset':True,                     # 不要重置App
    'newCommandTimeout':6000,
    'automationName':'UiAutomator2'
}

# 连接Appium Server,远程路径默认填写wd/hub
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)

# 设置缺省等待时间
driver.implicitly_wait(5)

# 如果有登录或注册弹框,点击x
try:
    cancel = driver.find_element(By.ID,"close").click()
except Exception:
    print("NoSuchElement:close")

# 如果有“青年保护”界面,点击“我知道了”
try:
    iknow = driver.find_element(By.ID,'test3').click()
except Exception:
    print("NoSuchElement:test3")

# 根据id定位搜索位置框,点击
driver.find_element(By.ID,'expand_search').click()


# 根据id定位搜索输入框,点击
sbox = driver.find_element(By.ID,'search_src_text')
sbox.send_keys('RNG')

# 输入回车键,确定搜索
# driver.press_keycode(66)
# driver.press_keycode(AndroidKey.ENTER)
# UiAutomator2中press_keycode有bug,改用以下方式进行"回车"操作
driver.execute_script("mobile:performEditorAction",{"action":"search"})


# 关注 “RNG电子竞技俱乐部” 账号
driver.find_element(By.ID,'follow').click()

input('*********Press to quit*********')

driver.quit()

你可能感兴趣的:(自动化测试,android,python,测试工具)