For example, consider the below html tags, where I need to get the exact index/position of the text, three
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
The expected value is '3'
You could do this:
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's implementation of Selenium is such that you can do comparisons between WebElement objects with == and thus index works. If you are working with a language that does not do this, you'd have to get the identifier that Selenium assigns to each WebElement object. On Python that's the .id property. In other languages you have a getId() or get_id() method to get the id. Then you can compare WebElement objects by identifier.
If the jsbin becomes inaccessible, this is the relevant HTML in it:
<body>
<table>
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
</table>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With