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

Hfrav :

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 "#", so the id's separate the downloads.

I need to find the name of that id element in the td. That is: I know the table row has an id element, and I know part of the name, and I need to get the exact name.

I'm accessing each row one at a time, so I only need to look within ONE td at a time. No need to look through the whole table.

I know well how to find an element when I know the name. But to find the element when I only know the type is another thing.

...
<tr>
 <td class="journalTable-journalPost"
  <a class="htext-small" href="#" id="downloadJournalPost-345">Download</a>
 </td>
</tr>
<tr>
 <td class="journalTable-journalPost"
  <a class="htext-small" href="#" id="downloadJournalPost-346">Download</a>
 </td>
</tr>
...

I cannot find any method(s) in the webdriver that lets me find an element by type.

Partial name would work, since the id's get the name "downloadJournalPost-xxx", where only xxx changes. But link text is the only value I can find which lets me search for a partial match.

EDIT: More complete markup.

<td class="journalTable-journalpost">
 <span class="hb-tekst--sekundar">In <!----><est-ikon class="ng-star-inserted">
  <div aria-hidden="true" class="hb-ikon hb-ikon--pil3-inn  ">
   <svg focusable="false">
    <use xlink:href="#ikon-pil3-inn"></use>
   </svg>
  </div></est-ikon><!----></span>
 <span class="hb-tekst--mellomTittel hb-avstandIngen"> Application and attachments</span>
 <a class="hb-tekst--liten" href="#" id="lastNedJournalPost-2892">Download journal post</a>
</td>
DebanjanB :

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);
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=75775&siteId=1