使用 Python 在 Selenium 中第二次出现元素后获取 td 的文本
Get text of td following the second occurrence of an element in Selenium using Python
我正在尝试查找表单中备注字段后的文本。但是,table 有多个备注字段。我希望能够在第二个备注字段的 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
但是,我需要从第二个备注栏中抓取内容。这必须基于 'Remarks' 出现的索引来完成,而不是基于索引。我想尝试这样的事情:
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")
据了解,这些都不起作用。有没有办法做到这一点?使用 'the field after the nth occurrence of Remarks' 行的命令是我正在寻找的。
P.S。这必须使用 xpath 来完成。原因是,我正在尝试将同事代码从另一个应用程序转换为 selenium,该应用程序的一切都围绕着 xpath。
我正在使用 Selenium-2.44.0 和 Python 2.7.
在 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
我正在尝试查找表单中备注字段后的文本。但是,table 有多个备注字段。我希望能够在第二个备注字段的 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
但是,我需要从第二个备注栏中抓取内容。这必须基于 'Remarks' 出现的索引来完成,而不是基于索引。我想尝试这样的事情:
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")
据了解,这些都不起作用。有没有办法做到这一点?使用 'the field after the nth occurrence of Remarks' 行的命令是我正在寻找的。
P.S。这必须使用 xpath 来完成。原因是,我正在尝试将同事代码从另一个应用程序转换为 selenium,该应用程序的一切都围绕着 xpath。
我正在使用 Selenium-2.44.0 和 Python 2.7.
在 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