Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index/position of the tag using text in Selenium WebDriver?

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'

like image 365
Prashanth Sams Avatar asked Jan 29 '26 03:01

Prashanth Sams


1 Answers

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>
like image 99
Louis Avatar answered Feb 01 '26 05:02

Louis