简体   繁体   中英

How to fetch multiple ID using xpath or cssSelector if its sharing the same classname

Was trying to fetch ID but was throwing no element found exception for the following code:

System.out.println(driver.findElement(By.xpath("//a[@class='activity'][contains(.,'First Testing')]")).getAttribute("id");)

System.out.println(driver.findElement(By.xpath("//a[@class='activity'][contains(text(), 'Second Testing')]")).getAttribute("id"));

The above two code lines didn't worked threw no elements found exception

Please find the HTML:

<a id="id_106" class="activity"> 
<strong>teena</strong>: <label id="check_label">
<em class="Highlight" 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="79991">Test</em> First Testing
</label>
</a>

<a id="id_109" class="activity"> 
<strong>maria</strong>: <label id="check_label">
<em class="Highlight" 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="amazon" loopnumber="791951">Test</em> Second Testing 
</label>
</a>

Here since contents inside strong tag is not constant and only element constant is text values in label tag (First Testing/Second Testing) and classname is same

Expected output:

id_106
id_109

To print the texts id_106 and id_109 you can use the following locator strategies :

  • To print id_106 :

     System.out.println(driver.findElement(By.xpath("//label[@id='check_label' and contains(.,'First Testing')]//parent::a")).getAttribute("id"));
  • To print id_109 :

     System.out.println(driver.findElement(By.xpath("//label[@id='check_label' and contains(.,'Second Testing')]//parent::a")).getAttribute("id"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM