As part of automation testing, we often encounter scenarios where we need to handle dynamic elements in Selenium. These elements may not have static IDs or consistent attributes, making them tricky to locate. Locating dynamic elements using other locator types, such as id or name, can be challenging, especially when those attributes change frequently. In such cases, XPath and CSS Selectors become powerful tools to identify elements based on patterns or relationships in the DOM.
Below is an example HTML snippet where elements are dynamic, and we’ll demonstrate how to locate them effectively using XPath and CSS:
HTML code:
<ul class=’fruits’ id=’fruit-list’>
<li>Apple</li>
<li>Orange</li>
<li>Banana</li>
</ul>
In the above HTML code, the <ul> element has a unique id, but the individual <li> elements do not have specific IDs.
If the requirement is to select the second <li> element (Orange), we can use XPath or CSS selectors as shown below.
XPath to find the element:
WebElement elem = driver.findElement(By.xpath(“(//ul[@id=’fruit-list’]//li)[2]”));
CSS Selector to find the same element:
WebElement elem = driver.findElement(By.cssSelector(“#fruit-list li:nth-of-type(2)”));