Search code examples
seleniumselenium-webdriverxpathselenium-chromedriverwebdriver

How to fetch second id from <div> tag using xpath if its has multiple classes with same classname and multiple div tag


Observed that the only unique value is id, how can we fetch in this case.

Please Find the HTML :

<div id="0007" data-activity-type="CompatCheck" class="Activity"></div>
                                
<div id="110007" data-activity-type="CompatCheck" class="Activity"</div>

While trying to use following code line :

findElement(By.xpath("//div[@data-activity-type='CompatCheck']")).getAttribute("id");

I'm getting only first id i.e; 0007

but I need always the second id="110007", can you please suggest to get the second id

Expected output : 110007


Solution

  • In case you always need the second element id you can update your XPath accordingly.
    This should work:

    findElement(By.xpath("(//div[@data-activity-type='CompatCheck'])[2]")).getAttribute("id");