gpt4 book ai didi

selenium - 如何在 Selenium WebDriver 中使用文本获取标签的索引/位置?

转载 作者:行者123 更新时间:2023-12-02 21:32:02 25 4
gpt4 key购买 nike

例如,考虑下面的 html 标签,我需要在其中获取文本的确切索引/位置,三个

<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>

预期值为“3

最佳答案

你可以这样做:

from selenium import webdriver

driver = webdriver.Firefox()

# This is an actual bin with a test page in it.
driver.get("http://jsbin.com/wagonazipa")

# Obviously, this needs to be precise enough to find the tr
# you care about. Adapt as needed.
tr = driver.find_element_by_tag_name("tr")

# Find the element you care about. You might want to use td rather
# than *.
target = tr.find_element_by_xpath("*[. = 'three']")

# Get all the children of the row.
children = tr.find_elements_by_xpath("*")

# Get the index of target in the children list.
print children.index(target)

Selenium 的 Python 实现使您可以在 WebElement 对象与 == 之间进行比较,从而 index 起作用。如果您使用的语言不执行此操作,则必须获取 Selenium 分配给每个 WebElement 对象的标识符。在 Python 上,这是 .id 属性。在其他语言中,您可以使用 getId()get_id() 方法来获取 id。然后您可以通过标识符比较 WebElement 对象。

如果 jsbin 无法访问,这是其中的相关 HTML:

<body>
<table>
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
</table>
</body>

关于selenium - 如何在 Selenium WebDriver 中使用文本获取标签的索引/位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28877064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com