Get index/position of the tag using text in Selenium WebDriver
<p>Here is html chunk:</p>

<pre><code>&lt;tbody&gt;
 &lt;tr&gt;
  &lt;td&gt;&lt;td&gt;
  &lt;td&gt;
    &lt;img src="../imgs.gif"&gt;
  &lt;td&gt;
  &lt;td&gt;&lt;td&gt;
  &lt;td&gt;&lt;td&gt;
  &lt;td&gt;&lt;td&gt;
 &lt;/tr&gt;
&lt;/tbody&gt;
</code></pre>

<p>I want to iterate over <strong>&lt; td ></strong> attributes and and get the index position of <strong>&lt; img ></strong> attribute. In this case, the output should be <strong>"1"</strong>.</p>

<p>Tried a lot of xpath strategies including index-of(), count(), etree etc.</p>

<p>As I suspect, the following should be close.</p>

<pre><code>from selenium import webdriver

chrome_path = r"E:\chromedriver_win32\chromedriver.exe"
browser = webdriver.Chrome(chrome_path)

td = browser.find_element_by_xpath("//tbody//tr//td")
target = td.find_element_by_xpath("*[. = '../imgs.gif']")
children = td.find_elements_by_xpath("*")
print children.index(target)
</code></pre>

<p>How about identifying the image and counting the preceding td sibling and adding one to it.</p>

<pre><code>$x("count(//img/parent::td/preceding-sibling::td) + 1")
</code></pre>

python html selenium xpath