-
元素定位可以参考https://www.jianshu.com/p/81e12261a2fc
-
元素定位一只都是自动化测试中的一个痛点,这篇demo简单的描述下几种Android自动化中元素定位方法,话不多说,直接上代码;
# coding=utf8
import unittest
from appium import webdriver
from time import sleep
class AppTests(unittest.TestCase):
def setUp(self):
# 会话(Session)参数
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['deviceName'] = 'abc'
# desired_caps['app'] = r'E:\share\App\apks\ApiDemos-debug.apk'
desired_caps['appPackage'] = 'io.appium.android.apis'
desired_caps['appActivity'] = 'io.appium.android.apis.ApiDemos'
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
self.driver.implicitly_wait(10)
def tearDown(self):
sleep(2)
self.driver.quit()
def test1(self):
driver = self.driver
# 参数是控件的content-desc,假如元素中没有content-desc的话会报错
el = driver.find_element_by_accessibility_id('Animation')
el.click()
# .text() 根据控件的文本匹配
# 方法一:使用new UiSelector()
el = driver.find_element_by_android_uiautomator('new UiSelector().text("Animation");')
# 方法二:直接使用.text也可以定位到文本
el = driver.find_element_by_android_uiautomator('.text("Animation")')
# .textContains() 根据控件的部分文本匹配
el = driver.find_element_by_android_uiautomator('.textContains("ation")')
# .textStartsWith() 根据控件的文本开始部分匹配
el = driver.find_element_by_android_uiautomator('.textStartsWith("Ani")')
# .textMatches() 根据控件文本匹配的正则表达式匹配
el = driver.find_element_by_android_uiautomator('.textMatches("^An[a-z]{7}")')
el = driver.find_element_by_android_uiautomator('.textMatches("^An[a-z]{7,}")')
el = driver.find_element_by_android_uiautomator('.textMatches("^An[a-z]{7,10}")')
el = driver.find_element_by_android_uiautomator('.textMatches("^An[a-z]{2,3}tion$")')
# 使用多个条件匹配控件
# .className() 根据class匹配控件
el = driver.find_element_by_android_uiautomator('.text("Animation").className("android.widget.TextView")')
el = driver.find_element_by_android_uiautomator('.index(1).className("android.widget.TextView")')
# .description() 使用content-desc属性匹配
el = driver.find_element_by_android_uiautomator('.description("Animation")')
el = driver.find_element_by_android_uiautomator('.descriptionContains("Anima")')
# 层级定位
el = driver.find_element_by_android_uiautomator('.className("android.widget.ListView").childSelector(.description("Animation"))')
el = driver.find_element_by_android_uiautomator('.description("Animation").clickable(true)')
# .resourceId() 根据控件的resource-id匹配
# el = driver.find_element_by_android_uiautomator('.description("Animation").resourceId("android:id/text1")')
el = driver.find_element_by_android_uiautomator('.description("Animation").resourceIdMatches("android:id/text[123]")')
el.click()