Selenium WebDriver-使用cssSelector和第n个子元素查找元素 [英] Selenium WebDriver - Finding Elements using cssSelector and nth child
问题描述
<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>
我想找到相应的span元素.我想使用css选择器检查span元素的顺序.因此,当我使用Selenium IDE时,我将按照以下方式进行验证(使用第n个子概念).
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)|主页
verifyText | css = .title:nth(1)|帖子
verifyText | css = .title:nth(2)|活动
verifyText | css = .title:nth(3)|我的活动
verifyText | css = .title:nth(4)|评估
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
但是,当我在Selenium WebDriver中执行相同的操作时,我无法按照我使用Selenium IDE进行的顺序来定位元素.
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.
下面是我在WebDriver中使用的代码,它可以正常工作.
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
任何人都可以帮助我.
推荐答案
您可以像ul > li:nth-child(1)
这样从ul
生成css选择器.见下文:
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
作用范围也相同:
driver.findElement(By.cssSelector("ul > li:nth-child(1) > a > span")); >> home
这篇关于Selenium WebDriver-使用cssSelector和第n个子元素查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!