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

Time:01-17

Please find the HTML :

<div id="086" data-activity-type="CompatCheck" ></div>

Here only constant value is data-activity-type="CompatCheck" and class is same for all the other elements.

Can anyone suggest to print id using data-activity-type i.e. CompatCheck using xpath

Expected output:

086

CodePudding user response:

As the attribute data-activity-type="CompatCheck" is unique you can use it and you can use either of the following the following locator strategies::

  • Using cssSelector:

    System.out.println(driver.findElement(By.cssSelector("div[data-activity-type='CompatCheck']")).getAttribute("id"));
    
  • Using xpath:

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

Console output:

086

CodePudding user response:

With XPath or CSS Selectors you can locate web element based on any constant attribute value. I.e. it can be based on constant class name value or id or any other attribute. In your case the constant attribute value is data-activity-type="CompatCheck". So, you can locate this element by XPath or by CSS Selector and then extract the id attribute as following:
XPath

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

CSS Selector

driver.findElement(By.cssSelector("div[data-activity-type='CompatCheck']")).getAttribute("id");
  • Related