简体   繁体   English

如果共享相同的类名,如何使用 xpath 或 cssSelector 获取多个 ID

[英]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:试图获取 ID 但未针对以下代码抛出未找到元素的异常:

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:请找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这里因为强标签内的内容不是常量,只有元素常量是 label 标签(第一次测试/第二次测试)中的文本值,类名相同

Expected output:预计 output:

id_106
id_109

To print the texts id_106 and id_109 you can use the following locator strategies :要打印文本id_106id_109 ,您可以使用以下定位器策略

  • To print id_106 :打印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 :打印id_109

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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