【问题标题】:Selenium CSS selector for nth occurrence of td span:nth-child(2)Selenium CSS 选择器,用于第 n 次出现 td span:nth-child(2)
【发布时间】:2015-10-25 01:09:09
【问题描述】:

css 选择器td span:nth-child(2) 表示td 的第二个子节点span。我想选择第n个td span:nth-child(2),比如:

driver.find_element_by_css_selector("td span:nth-child(2):eq(4)")

我知道我可以使用

driver.find_elements_by_css_selector("td span:nth-child(2)")[4]

或 xpath 代替:

driver.find_elements_by_xpath('(//td/span[2])[4]')

我只是想知道我是否可以用 css 选择器做同样的事情。

【问题讨论】:

    标签: python selenium xpath css-selectors


    【解决方案1】:

    您不能使用 CSS 选择器来做到这一点。 :eq() 来自 jQuery,不属于任何标准。

    td:nth-child(4) span:nth-child(2) 意味着完全不同的东西,并且只会在非常特定的情况下工作,例如当恰好有一个表格行包含四个 td 元素时,所有这些元素都包含至少两个 span 子元素:

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

    它不会匹配你在这个例子中寻找的元素,因为每个tr只有两个td子元素,所以td:nth-child(4)永远不会匹配:

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

    如果您知道 td:nth-child(4) span:nth-child(2) 可以保证在您的情况下工作,请随意使用它。

    【讨论】:

    • 谢谢,我正在处理后一种情况。我会改用xpath
    【解决方案2】:

    如果我正确理解您的问题,您也可以在td 上使用nth-child()

    driver.find_elements_by_css_selector("td:nth-child(4) span:nth-child(2)")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2015-11-04
      • 2011-03-11
      • 1970-01-01
      • 2012-09-25
      • 2018-07-09
      • 2023-03-25
      相关资源
      最近更新 更多