Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium CSS selector for nth occurrence of td span:nth-child(2)

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.

like image 371
LittleQ Avatar asked Aug 03 '15 02:08

LittleQ


1 Answers

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.

like image 122
BoltClock Avatar answered Sep 22 '22 05:09

BoltClock