(HTML) Selecting the next matching element, by CSS selector?

时间:2015-06-25 18:18:23

标签: html css xpath css-selectors webdriver

I'm using the CSS selector in selenium webdriver.

Let's say I have a DOM that looks like this:

<div class="test">
    <a class="example"> Comet </a>
</div>
<div class="test">
    <a class="example"> Asteroid </a>
</div>
<div class="test">
    <a class="example"> Planet </a>
</div>

Let's say I want to match the tag with "Asteroid" in it. If I'm using the CSS selector, I can do something like this: div.test > a.example

Only problem is that this will match all three. Using an xpath, I could do something like this: (//div/a[@class='example'])[2] This would tell it to select the second matching element.

Is there a way with the CSS selector that I could do the same thing? Just select the 2nd or 3rd matching element? I tried :nth-child(), but that seems to only work on the children of a specified node, and doesn't seem to work like the xpath example I gave, or maybe I'm doing it wrong.

2 个答案:

答案 0 :(得分:4)

Is this what you mean?

.test:nth-of-type(2) .example{color:red;}
<div class="test">
    <a class="example"> Comet </a>
</div>
<div class="test">
    <a class="example"> Asteroid </a>
</div>
<div class="test">
    <a class="example"> Planet </a>
</div>

答案 1 :(得分:0)

The reason it is selecting the child is because that is how it is supposed to work. If you wrapped what you have in another div it will work. For arguments sake, if you wrapped your code in a div <div id="list">, you can use XPATH in the way you describe.

相关问题