简体   繁体   中英

Selenium with JS how to count child elements inside parent

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM