0

I got the following HTML structure:

<ul id="test">
   <li><div><span>name one</span></div></li>
   <li><div><span>name two</span></div></li>
   <li><div><span>name three</span></div></li>
   <li><div><span>name four</span></div></li>
</ul>

My first question is how could I get the number of li tags inside using Selenium. In cypress is simple as:

cy.get('#test').children().should('have.length', 4)

And my second question is: How could I get the nth-child inside this ul? I tried by doing this:

const firstName = await d.driver.findElements(By.xpath("//ul[contains(@id, 'test')]/li/div/span")).getText()

Here I got the first li text, but how could I get the text of the remaining lists inside?

const secondManualName = await d.driver.findElement(By.cssSelector("ul[contains(@id, 'test')]>li:nth-child(2)>div>span")).getText()

In the above line of code it is throwing an error, that there is not such a function. I cannot understand why the selenium documentation is so incomplete. I will appreciate if you recommend me some good website for selenium with JS( with some nice examples ).

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
DragoJokera
  • 825
  • 2
  • 16
  • 23

1 Answers1

0

To get the nth <li> child inside the <ul> you can use either of the following Locator Strategies:

  • cssSelector:

    ul#test li:nth-child(n) > div > span
    where, n = 2,3,4 etc.
    
  • Effective line of code:

    await driver.findElement(By.css("ul#test li:nth-child(2) > div > span")).getText()
    
  • xpath:

    //ul[@id='test']//following::li[n]/div/span
    where, n = 2,3,4 etc.
    
  • Effective line of code:

    await driver.findElements(By.xpath("//ul[@id='test']//following::li[2]/div/span")).getText()
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352