Appium入坑指南——第一个测试用例(Python篇)

安装Appium Python Client

三种安装方式:

  1. pip在线安装(推荐方式):pip install Appium-Python-Client

  2. 在Pypi上下载源码安装

    1
    2
    3
    tar -xvf Appium-Python-Client-X.X.tar.gz
    cd Appium-Python-Client-X.X
    sudo python3.6 setup.py install
  3. 通过git安装

    1
    2
    3
    git clone git@github.com:appium/python-client.git
    cd python-client
    sudo python3.6 setup.py install

编写测试用例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from appium import webdriver

desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.0'
desired_caps['deviceName'] = 'SA17607795'
desired_caps['appPackage'] = 'com.android.calculator2'
desired_caps['appActivity'] = '.Calculator'
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
driver.find_element_by_android_uiautomator('new UiSelector().text("1")').click()
driver.find_element_by_android_uiautomator('new UiSelector().text("2")').click()
driver.find_element_by_android_uiautomator('new UiSelector().text("3")').click()
driver.find_element_by_android_uiautomator('new UiSelector().text("+")').click()
driver.find_element_by_android_uiautomator('new UiSelector().text("3")').click()
driver.find_element_by_android_uiautomator('new UiSelector().text("2")').click()
driver.find_element_by_android_uiautomator('new UiSelector().text("1")').click()
driver.find_element_by_android_uiautomator('new UiSelector().text("=")').click()
driver.quit()

执行命令:

python3.6 android_calculator.py

遇到的问题

  1. 问题:driver.find_element_by_name("=").click()
1
selenium.common.exceptions.InvalidSelectorException: Message: Locator Strategy 'name' is not supported for this session

谷歌后得知:通过name获取控件的方式在Appium 1.5就被移除了。

  1. 问题:driver.find_element_by_accessibility_id('com.android.calculator2:id/digit_1').click()

报错:

1
selenium.common.exceptions.NoSuchElementException: Message: An element could not be located on the page using the given search parameters.

经请教后得知在最新版本Appium中不再支持通过id的方式来定位元素。

改用:driver.find_element_by_android_uiautomator('new UiSelector().text("1")').click(),可运行

  1. 问题: 执行appium程序时遇到如下报错,ImportError: cannot import name ‘InvalidArgumentException’,

报错原因 selenium.common.exceptions.py中未定义InvalidArgumentException类,导致出现该报错,我的解决办法是

在selenium.common.exceptions.py中直接定义了InvalidArgumentException,代码如下(C:\Users\Python35\Lib\site-packages\selenium\common)找到exceptions.py,添加下面的代码,再次执行脚本,ok.

1
2
3
4
class InvalidArgumentException(WebDriverException):
"""
"""
pass