【问题标题】:Get text of td following the second occurrence of an element in Selenium using Python使用 Python 在 Selenium 中第二次出现元素后获取 td 的文本
【发布时间】:2015-03-16 22:35:40
【问题描述】:

我正在尝试在表单中的备注字段后查找文本。但是,该表有多个备注字段。我希望能够在第二个备注字段的 td 之后的 td 中获取文本。我有以下html:

<table>
  <tbody>
    <tr>...</tr> 
    <tr>...</tr>
    <tr>
      <td>Remarks:</td>
      <td>this is the first remarks field
    </tr>
    <tr>
      <td>AnotherField:</td>
      <td>Content of that field</td>
    </tr>
    <tr>
      <td>Remarks:</td>
      <td>this is the second remarks field</td>
    </tr>
    <tr>...</tr>
  </tbody>
</table>

要从第一个备注字段中获取文本,我可以执行以下操作:

ret = driver.find_element_by_xpath("//td[contains(text(),'Remarks')]/following::td")
print ret.text

但是,我需要从第二个备注字段中获取内容。这必须基于“备注”出现的索引,而不是基于索引。我想尝试这样的事情:

ret = self.driver.find_element_by_xpath("//td[contains(text(),'Remarks')][1]/following::td")

或:

rets = self.driver.find_elements_by_xpath("//td[contains(text(),'Remarks')]")[1]
ret = elements.find_element_by_xpath("/following::td")

可以理解,这些都行不通。有没有办法做到这一点?使用类似于“第 n 次出现备注后的字段”的命令是我正在寻找的。​​p>

附:这必须使用 xpath 来完成。原因是,我正在尝试将同事代码从另一个应用程序转换为 selenium,该应用程序的一切都围绕 xpath。

我正在使用 Selenium-2.44.0 和 Python 2.7。

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    XPath 中的索引从 1 开始:

    (//td[contains(., 'Remarks')]/following-sibling::td)[2]
    

    或者,您可以使用find_elements_by_xpath() 并获取第二项:

    elements = self.driver.find_elements_by_xpath("//td[contains(., 'Remarks')]/following-sibling::td")
    print elements[1].text
    

    【讨论】:

    • 不错的答案,这真的很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多