Selenium WebDriver - Finding Elements using cssSel

2019-02-09 06:46发布

问题:

<ul>
<li class="active">
    <a href="#">
    <i class="fa fa-home"></i><br>
    <span class="title">Home</span>
    </a>
</li>

<li>
    <a href="#">
    <i class="fa fa-rss-square"></i><br>
    <span class="title">Posts</span>
    </a>
</li>

<li>
    <a href="#">
    <i class="fa fa-calendar"></i><br>
    <span class="title">Events</span>
    </a>
</li>

<li>
    <a href="#">
    <i class="fa fa-bar-chart-o"></i><br>
    <span class="title">My Activity</span>
    </a>
</li>

<li>
    <a href="#">
    <i class="fa fa-edit"></i><br>
    <span class="title">Assessments</span>
    </a>
</li>
</ul>

I want to locate the respective span element. I want to check the order of the span elements using css selector. So when I use selenium IDE,I will verify it like below(using nth child concept).

verifyText | css=.title:nth(0) | Home
verifyText | css=.title:nth(1) | Posts
verifyText | css=.title:nth(2) | Events
verifyText | css=.title:nth(3) | My Activity
verifyText | css=.title:nth(4) | Assessments

But when I do the same thing in Selenium WebDriver I am not able to locate the elements with the order which I did using Selenium IDE.

Below are the codes that I used in WebDriver and it dint work.

driver.findElement(By.cssSelector(".title:nth(0)")); // to locate the "Home" element

driver.findElement(By.cssSelector(".title:nth-of-type(0)")); // to locate the "Home" element

driver.findElement(By.cssSelector(".title:nth-child(0)")); // to locate the "Home" element

Could anyone please help me.

回答1:

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


回答2:

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


回答3:

<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