Home > front end >  How to fetch id from <div> tag using xpath in efficient way
How to fetch id from <div> tag using xpath in efficient way

Time:01-18

Tried many approach to get the id but I'm not able to find exact Id or efficient result as there multiple ids and its sharing multiple same class.

Tried following approaches but I'm not getting the exact Id needed

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

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

//Approach 3
driver.findElement(By.xpath("//div[@data-activity-type='CompatCheck'] and contains(.,'AndroidTesting')]")).getAttribute("id"));

Please find the HTML Code below :

      <div> 
         <strong>Reena</strong>: 
         <label id="compatcheck_label">
         <em  style="padding: 1px; box-shadow: rgb(229, 229, 229) 1px 1px; border-radius: 3px; 
background-color: rgb(0, 191, 255); color: rgb(0, 0, 0); font-style: inherit;" match="test" loopnumber="472046515">Test</em>device testing - AndroidTesting
         </label>
        </div>
        <div>
         <span style="float: none;" >(Special Tag) 
        </span>
         <label id="label_1100"></label>                            
         <span style="float: none;">0d 4h 39m 49s</span>
        </div>
        <div id="div_1100" data-activity-type="CompatCheck" >
        </div>

From the above HTML code observed that label id and div id is same (1100) , and what differs from other class is "device testing - AndroidTesting"

Is there any approach we can get either label id or div id (as both are same) by using "device testing - AndroidTesting" as it is the only unique and constant element.

Expected output using "device testing - AndroidTesting" as unique

label_1100
 div_1100



                                

CodePudding user response:

As per the given HTML to print the desired texts you can use the following following locator strategies:

  • Printing label_1100:

    System.out.println(driver.findElement(By.xpath("//label[@id='compatcheck_label'][contains(., 'AndroidTesting')]//following::div//label[1]")).getAttribute("id"));
    
  • Printing div_1100:

    System.out.println(driver.findElement(By.xpath("//label[@id='compatcheck_label'][contains(., 'AndroidTesting')]//following::div[2]")).getAttribute("id"));
    
  • Related