Skip to content
Advertisement

Selenium and Java: Finding nested elements without good id-s or selectors

I’m having some trouble finding the text contents of

  • elements in a page, where – sadly – the hierarchy of the small kings creating common components for the Angular applications makes it all but impossible to impose intelligent selectors for the markup.

    This is the list in question, with all the tags from :

    <app-root....
     <app-soknad....
      <app-oppsymmeriing-side
       <main class="hb-side-hovedomrade">
        <section class="hb-seksjon">
         <app-oppsummering-personer-i-boligen>
          <div data-e2e-selector="personerCard" class="hb-card">
           <div class="hb-card-topp"><h3 translate="" class="hb-card-tittel">Personer i boligen</h3></div>
            <div class="hb-card-body">
             <ul class="hb-liste hb-liste--minimal">
              <li><span aria-hidden="false" class="hb-ikon hb-ikon--storrelse250"></span>E2efornavn E2eetternavn </li>
              <li><span aria-hidden="false" class="hb-ikon hb-ikon--storrelse250"></span>Gutt, 9 år </li>
             </ul>
            </div>
    

    Java code:

     List<WebElement> we = driver.findElements(By.cssSelector("[data-e2e-selector=personerCard]>div>div>li"));
    
    List<String> beboere = driver.findElements(By.cssSelector("[data-e2e-selector=personerCard]>div>div>li")).stream().map(WebElement::getText).collect(Collectors.toList());
    

    I’m unable to get any results with the above code. I shouldn’t have to specify all the tags preceding the

  • , should I? It’s not possible to put a selector on the , which would have been the best solution. Is it perhaps possible to use the with the data-e2e-selector?
  • Advertisement

    Answer

    use selector

    .hb-liste.hb-liste--minimal > li
    

    https://seleniumbyexamples.github.io/cssselectorclassmultiple

    Advertisement