Selenium WebDriver - Finding Elements using cssSelector and nth child

浪尽此生 提交于 2019-11-30 06:57:28
Mesut GÜNEŞ

You can generate the css-selector from ul like ul > li:nth-child(1) for home. See below:

driver.findElement(By.cssSelector("ul > li:nth-child(1)")); >> home
driver.findElement(By.cssSelector("ul > li:nth-child(2)")); >> posts
driver.findElement(By.cssSelector("ul > li:nth-child(3)")); >> events

also reachin span is the same:

driver.findElement(By.cssSelector("ul > li:nth-child(1) > a > span")); >> home

do you need css specifically? if not, you can also go for xpath, which imho "reads" better/clearer:

driver.findElement(By.xpath("(//span[@class='title'])[0]")); // home
driver.findElement(By.xpath("(//span[@class='title'])[1]")); // posts
...
<body>
        <div class=parent>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </body>

If you already have the parent element and just need to find nth child

parent.find_element_by_css_selector('div:nth-child(2)')

would select the third div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!