Wednesday, 4 September 2013

Xpath Patterns for Locating WebElements


contains()
Elements can also be located using partial text from an attribute value.
i.e., any attribute, class/id has value: say,  'your class is here';  Here, you can make use of contains for locating elements with partial text, 'your class' truncating 'is here'.
1|
//input[contains(@class, 'your partial class')]
2|
//input[contains(text(),'your partial text')]


not(contains())
'not contains'  is just the reverse of  'contains'. 
1|
//input[not(contains(@class, 'your class'))]

Excercise |1|
<ul id="subject">
   <li class="root">
      <a id="abc">"Physics"</a>
   </li>
   <li class="root">
      <a id="abcd">"Chemistry"</a>
   </li>
   <li class="root">
      <a id="abcde">"Mathematics"</a>
   </li>
</ul>

List<WebElement> elements = driver.findElements(By.xpath("//ul[@id='subject']/li[not(contains(.,'Chemistry'))]"));
//driver.findElements(By.xpath("//ul[@id='subject']/li[not(contains(a,'Chemistry'))]")); -Alternate Step
System.out.println(elements.size());

for (int i = 0; i < elements.size(); i++) {
System.out.println(ass.get(i).getText());
}
OUTPUT| 
Physics
Mathematics


text()
The inner text can be used to find Elements.
1|
//input[text()='your text']
2|
//div[contains(text(), 'your text')]


starts-with()
Finds dynamic elements using start of an Element. If your dynamic ids have the format <input id="text-12345" /> where 12345 is a dynamic number you could use the following XPath: //input[starts-with(@id, 'text-')]

2 comments: