How to extract the dynamic values of the id attributes of the table elements using Selenium and Java

久未见 提交于 2019-12-01 19:36:11

To print the List of id attribute of the element you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use Java8 stream() and map() and you can use either of the following Locator Strategies:

  • cssSelector:

    List<String> myID = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("td.journalTable-journalPost>a.htext-small"))).stream().map(element->element.getAttribute("id")).collect(Collectors.toList());
    System.out.println(myIDs);
    
  • xpath:

    List<String> myIDs = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//td[@class='journalTable-journalPost']/a[@class='htext-small' and text()='Download']"))).stream().map(element->element.getAttribute("id")).collect(Collectors.toList());
    System.out.println(myIDs);
    

Until you find the element first, you can't retrieve the attribute values of it.

Use findElements method to fetch all links using the following locator

table tr td[class='journalTable-journalPost'] a

Then iterate through each element using for-each to fetch id for each element.

Sample code:

List<WebElement> listOfLinks = driver.findElements(By.cssSelector("table tr td[class='journalTable-journalPost'] a"));

for(WebElement link: listOfLinks) {
     System.out.println("id:" + link.getAttribute("id"));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!