例如,考虑以下html
标记,我需要获取文本的确切索引/位置three
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
预期值为 3 &#39;
答案 0 :(得分:4)
以下是使用 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));
答案 1 :(得分: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>