Search code examples
htmlrubyseleniumxpath

How to find nearest parent by tag_name with selenium


I'm working with "Table styled" web site by using selenium-webdriver.

There are a lot of nesting of tables and there are no id or name attributes of them.

So I decided to get header text in a table to find a place of data like this.

 driver = Selenimum::WebDriver.for :firefox
 element = driver.find_element(:xpath,
   "//font[@color='#FFFFFF' and text()='some probably unique text']")

from HTML like this.

<table><tbody>
...
<table><tbody><tr><td><font color="#FFFFFF">
  some probably unique text
</font></td></tr></table>
...
</tbody></table>

I want to get the inside table element from font element that I got in above code. I know I can get with element.find_element(:xpath, "../../../.."), but it's a little disgusting.

I want to specify a tag name at least like this element.find_element(:xpath, "../*/table").

Is there way to do this?


Solution

  • You can use XPath axes ancestor.

    element = driver.find_element(:xpath, ".//font[@color='#FFFFFF' and text()='some probably unique text']/ancestor::table")
    

    Or nested XPath: not for nested tables situation like yours

    element = driver.find_element(:xpath, ".//table[.//font[@color='#FFFFFF' and text()='some probably unique text']]")