1. 通过xpath找元素
编写xpath捕获元素:
a. 以 class开头 //class
b. [OPTIONAL] 加attributes @attribute=“blah”
E.g.: 用xpath 定位计算器的 7
用Python 和 Appium, 对应的写法如下:
2. 通过Android UIAutomator 找元素
用UiSelector捕获元素 UI elements:
a. 已new UiSelector object 开头new UiSelector()
b. dot-add any of the other properties of the element .text()
E.g.: 定位计算器的 7 :
用Python 和 Appium, 对应的写法如下:
注意:此方法使用诸如text,content-desc,resorurce id等属性来查找元素。有关详细信息,请参阅此链接。
以下是识别Appium特定元素的一些快捷方式:
- 通过 accessibility ID捕获元素: android机,你可以用content-desc的字符串
E.g.: To identify the delete button in the calculator
- 通过 Id捕获元素: 对应 resource-id field
E.g.: To identify the number 7 in the calculator app
- 通过 class name捕获元素:
E.g.: To find the text/results box in the calculator app
实例: 应用不同的定位策略的Appium + Python 脚本
以下提供一个功能齐全的Python脚本供您练习定位器策略。挑战自己,在计算器应用程序中识别不同的元素,并对此脚本进行相应的更改。
"""
Qxf2: Example script to run one test against calculator app
The test will show you how you can find UI elements by various methods like xpath, id, accessibility_id and android UIautomator
on a android calculator app
"""
import os
import unittest, time
from appium import webdriver
from time import sleep
class Android_Calculator(unittest.TestCase):
"Class to run tests for android calculator"
def setUp(self):
"Setup for the test"
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '4.4'
desired_caps['deviceName'] = 'Moto E'
# Get the package and activity name of the calculator to launch the calculator app
desired_caps['appPackage'] = 'com.android.calculator2'
desired_caps['appActivity'] = 'com.android.calculator2.Calculator'
self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
def tearDown(self):
"Tear down the test"
self.driver.quit()
def test_calculator(self):
"Testing android calculator"
self.driver.implicitly_wait(10)
# Find the UI element using xpath
self.driver.find_element_by_xpath("//android.widget.Button[@text='7']").click()
self.driver.find_element_by_xpath("//android.widget.Button[@resource-id='com.android.calculator2:id/mul']").click()
# Find UI element using id
self.driver.find_element_by_id("com.android.calculator2:id/digit7").click()
# Find UI element using accessibility_id
self.driver.find_element_by_accessibility_id('delete').click()
# Find UI element using android UIautomator
self.driver.find_element_by_android_uiautomator('new UiSelector().text("3")').click()
self.driver.find_element_by_android_uiautomator('new UiSelector().resourceId("com.android.calculator2:id/equal")').click()
# Find UI element using class name
result=self.driver.find_element_by_class_name("android.widget.EditText")
print result.get_attribute('text')
#---START OF SCRIPT
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(Android_Calculator)
unittest.TextTestRunner(verbosity=2).run(suite)