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

后端 未结 2 1309
半阙折子戏
半阙折子戏 2020-12-21 03:29

I have a table where each row will have a download link with a (partly) auto-generated id element. The reason for this is that the actual href-element will allways be \"#\",

相关标签:
2条回答
  • 2020-12-21 04:00

    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"));
    }
    
    0 讨论(0)
  • 2020-12-21 04:18

    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);
      
    0 讨论(0)
提交回复
热议问题