How to extract the dynamic values of the id attributes of the table elements using Selenium and Java
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"));
}
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);