简体   繁体   中英

How can I get the last element using Xpath in Appium

For example, I have message elements in my Android app and all of them have a resource-id called "message_view" . What I want is to get the last message with this resource-id using Xpath only. I have tried to use [last()] , but it does not work:

driver.findElement (By.xpath ("//*[contains(@resource-id,'message_view')][last()]"));

I know that I can use findElements() , and then .get(list.size() - 1) . But I want to understand how can I do this with Xpath only.

In Xpaths, [] has a higher precedence over // , so in your given Xpath, the last() doesn't work because it's being executed first rather than last. Use a pair of parenthesis in order to force this to work as you expect:

(//*[contains(@resource-id,'message_view')])[last()]

You need to wrap locator with () , as it was mentioned in another answer.

I will explain difference between //locator[last()] and (//locator)[last()]

Let's imagine you have following DOM:

<div>
  <div>
   <p1></p1> // 1
   <p1></p1> // 2
  </div>
  <div>
   <p1></p1> // 3
   <p1></p1> // 4
  </div>
</div>

With //p1[last()] you'll find all p1 elements, that ARE last elements in their nodes (last of siblings), so it's 2nd and 4th p1 element.

By (//locator)[last()] locator, you'll find all p1 nodes, and pick the last one (which will be actually the last p1 node in DOM), so it's 4th p1 element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM