元素定位與交互
Appium支持一個Webdriver元素定位方法的子集
find by "tag name" (i.e., 通過UI的控件類型)
find by "name" (i.e., 通過元素的文本, 標簽, 或者開發同學添加的id標示, 比如accessibilityIdentifier)
find by "xpath" (i.e., 具有一定約束的路徑抽象標示, 基于XPath方式)
###標簽名抽象映射
你可以使用UIAutomation的控件類型用于標簽名, 或者使用簡化的映射, 可以參考下如下例子
https://github.com/appium/appium/blob/master/lib/uiauto/lib/mechanic.js#L29
(官方文檔外的補充)
對于Android下的元素對應, 可以參考
https://github.com/appium/appium/blob/master/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/AndroidElementClassMap.java
例子
找到屏幕上所有的UIAButtons
WD.js:
driver.elementsByTagName('button', function(err, buttons) {
// tap all the buttons
var tapNextButton = function() {
var button = buttons.shift();
if (typeof button !== "undefined") {
button.click(function(err) {
tapNextButton();
})
} else {
driver.quit();
}
}
tapNextButton();
});
Ruby:
buttons = @driver.find_elements :tag_name, :button
buttons.each { |b| b.click }
Python:
[button.click() for button in driver.find_elements_by_tag_name('button')]
找到所有文本內容(或者accessibilityIdentifier)為"Go"的元素
WD.js:
driver.elementByName('Go', function(err, el) {
el.tap(function(err) {
driver.quit();
});
});
Ruby:
@driver.find_element(:name, 'Go').click
Python:
driver.find_element_by_name('Go').click()
找到以"Hi, "開頭的導航條元素
WD.js:
driver.elementByXpath('//navigationBar/text[contains(@value, "Hi, ")]', function(err, el) {
el.text(function(err, text) {
console.log(text);
driver.quit();
});
});
Ruby:
@driver.find_element :xpath, '//navigationBar/text[contains(@value, "Hi, ")]'
通過tagName查找元素
Java:
driver.findElement(By.tagName("button")).sendKeys("Hi");
WebELement element = findElement(By.tagName("button"));
element.sendKeys("Hi");
List elems = findElements(By.tagName("button"));
elems.get(0).sendKeys("Hi");
Python:
driver.find_elements_by_tag_name('tableCell')[5].click()
你也可以通過一行命令來完成元素的查找和交互(只適用于IOS)
舉個例子, 你可以通過一次調用來實現查找一個元素并點擊它, 使用的命令是mobile: findAndAct
Python:
args = {'strategy': 'tag_name', 'selector': 'button', 'action': 'tap'}
driver.execute_script("mobile: findAndAct", args)
用一個滑動手勢進行下拉刷新
Python:
js_snippet = "mobile: swipe"
args = {'startX':0.5, 'startY':0.2, 'startX':0.5, 'startY':0.95, 'tapCount':1, 'duration':10}
driver.execute_script(js_snippet, args)
備注: driver.execute_script() 可以在 Automating Mobile Gestures: Alternative access method) 找到說明
使用Appium Inspector來定位元素
(翻譯備注: 這個工具目前只有Mac版本, 如果你使用的是windows, 可以使用android自帶的traceview工具來獲得元素的位置)
Appium提供了一個靈活的工具Appium Inspector, 允許你在app運行的時候, 直接定位你正在關注的元素. 通過Appium Inspector(靠近start test按鈕的i標示文本), 你可以通過點擊預覽窗口上的控件來獲得它的name屬性, 或者直接在UI導航窗口中定位
概述
Appium Inspector有一個簡單的布局, 全部由如下窗口組成.
UI導航器, 預覽, 錄制與刷新按鈕, 和交互工具
例子
啟動Appium Inspector后, (通過點擊app右上的小"i"按鈕), 你可以定位任何預覽窗口中的元素. 作為測試, 我正在查找id為"show alert"的按鈕
要找到這個按鈕的id, 在定位預覽窗口中我點擊了"show alert"按鈕, Appium Inspector在UI導航窗口中高亮顯示了這個元素, 然后展示了剛被點擊按鈕的id和元素類型
原文轉自:http://testerhome.com/topics/167