如何在 Selenium WebDriver 中使用文本获取标签的 index/position?
How to get index/position of the tag using text in Selenium WebDriver?
例如,考虑下面的 html
标签,我需要在其中获取文本的确切 index/position,three
<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)
Python 的 Selenium 实现使得您可以在 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>
这里有一个使用 JAVA
,
的例子
driver.get("http://www.indiabookstore.net/");
WebElement list = driver.findElement(By.xpath("//ul[@class='nav navbar-nav navbar-right']"));
WebElement li = list.findElement(By.xpath("*[. = 'Offers']"));
List<WebElement> children = driver.findElements(By.tagName("li"));
System.out.println(children.indexOf(li));
例如,考虑下面的 html
标签,我需要在其中获取文本的确切 index/position,three
<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)
Python 的 Selenium 实现使得您可以在 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>
这里有一个使用 JAVA
,
driver.get("http://www.indiabookstore.net/");
WebElement list = driver.findElement(By.xpath("//ul[@class='nav navbar-nav navbar-right']"));
WebElement li = list.findElement(By.xpath("*[. = 'Offers']"));
List<WebElement> children = driver.findElements(By.tagName("li"));
System.out.println(children.indexOf(li));