Selenium WebDriver - 使用 cssSelector 和第 n 个子元素查找元素 [英] Selenium WebDriver - Finding Elements using cssSelector and nth child

查看:35
本文介绍了Selenium WebDriver - 使用 cssSelector 和第 n 个子元素查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

验证文本 |css=.title:nth(0) |主页
验证文本 |css=.title:nth(1) |帖子
验证文本 |css=.title:nth(2) |活动
验证文本 |css=.title:nth(3) |我的活动
验证文本 |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 >一样从ul生成css-selectorli:nth-child(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

reachin span 也是一样的:

also reachin span is the same:

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

这篇关于Selenium WebDriver - 使用 cssSelector 和第 n 个子元素查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆