3.2 KiB
Finding and interacting with elements
Appium supports a subset of the WebDriver locator strategies:
- find by "tag name" (i.e., ui component type)
- find by "name" (i.e., the text, label, or developer-generated ID a.k.a 'accessibilityIdentifier' of an element)
- find by "xpath" (i.e., an abstract representation of a path to an element, with certain constraints)
###Tag name mapping
You can use the direct UIAutomation component type name for the tag name, or use the simplified mapping (used in some examples below) found here:
https://github.com/appium/appium/blob/master/app/uiauto/lib/mechanic.js#L29
Issues
There's a known issue with table cell elements becoming invalidated before there's time to interact with them. We're working on a fix
Examples
Find all the UIAButtons on the screen
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')]
Find the element with the text (or 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()
Find the nav bar text element where the text begins with "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, ")]'
Find an element by tagName
Java:
driver.findElement(By.tagName("button")).sendKeys("Hi");
WebELement element = findElement(By.tagName("button"));
element.sendKeys("Hi");
List<WebElement> elems = findElements(By.tagName("button"));
elems.get(0).sendKeys("Hi");
Python:
driver.find_elements_by_tag_name('tableCell')[5].click()
FindAndAct
If you want, you can find and act on an element in a single command (iOS-only).
For example, you can find and click on an element in one call to Appium, using a special mobile: findAndAct command.
Python:
args = {'strategy': 'tag_name', 'selector': 'button', 'action': 'tap'}
driver.execute_script("mobile: findAndAct", args)
Pull to refresh using a swipe gesture
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)
Note: driver.execute_script() is explained in Automating Mobile Gestures: Alternative access method)