问题
The css selector td span:nth-child(2)
means the 2nd child node span
of td
. I wanna choose the nth td span:nth-child(2)
, something like:
driver.find_element_by_css_selector("td span:nth-child(2):eq(4)")
I know I can use
driver.find_elements_by_css_selector("td span:nth-child(2)")[4]
or xpath instead:
driver.find_elements_by_xpath('(//td/span[2])[4]')
I just wanna know if I can do the same thing with css selector.
回答1:
You can't do this with a CSS selector. :eq()
is from jQuery and not part of any standard.
td:nth-child(4) span:nth-child(2)
means something entirely different, and will only work in very specific situations, such as when there is exactly one table row with four td
elements all of which contain at least two span
children:
<body>
...
<table>
<!-- The first, or only, row in the entire document
with this many cells containing this many spans -->
<tr>
<td>
<span></span>
<span></span>
<td>
<span></span>
<span></span>
<td>
<span></span>
<span></span>
<td>
<span></span>
<span></span>
</table>
...
</body>
It won't match the element you're looking for in this example, because each tr
has only two td
children, so td:nth-child(4)
will never match:
<body>
...
<table>
<tr>
<td>
<span></span>
<span></span>
<td>
<span></span>
<span></span>
<tr>
<td>
<span></span>
<span></span>
<td>
<span></span>
<span></span> <!-- (//td/span[2])[4] -->
</table>
...
</body>
If you know td:nth-child(4) span:nth-child(2)
is guaranteed to work in your situation though, feel free to use it.
回答2:
If I am understanding your question correctly, you can use nth-child()
on the td
as well:
driver.find_elements_by_css_selector("td:nth-child(4) span:nth-child(2)")
来源:https://stackoverflow.com/questions/31778616/selenium-css-selector-for-nth-occurrence-of-td-spannth-child2