Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath element which contains an attribute and whose parent's parent contains another attribute

This is my first post here and since I've seen many great answers I thought I'd give it a try.

I'm trying to use XPath to obtain a specific element in an HTML document. Here is an example based off of the Google web page:

<html>
  <head>
    <title>XPath Test</title>
  </head>
  <body>
    <form name='f'>
      <table>
        <tbody>
          <tr>
            <td>
              <input name='q' type="text" />
            </td>
          </tr>
        </tbody>
      </table>
    </form>
  </body>
</html>

Using the example above (which is simplified for the purposes of asking for help), I would like to be able to find the input element whose name='q' and who has an ancestor who is 5 parents up with the name='f'.

For example if I were to do this in the syntax of S.W.A.T. which is an open-source web automation testing library located at http://ulti-swat.wikispaces.com, the syntax would be as follows:

|AssertElementExists|Expression|name=q;parentElement.parentElement.parentElement.parentElement.parentElement.name=f|input|

I just started learning XPath and am trying to understand how to combine predicates with axes. Is it possible to do expressions like this with XPath? If so can someone knowledgeable please help?

like image 228
gtaborga Avatar asked Feb 02 '10 01:02

gtaborga


People also ask

How do you write parent and child in XPath?

Start by writing out the selenium Xpath for the parent and then traverse to desired object using back slashes like so; Xpath Parent written as //div[@class='region region-navigation' using our previously shown syntax. Now you start to traverse through the HTML nodes down to desired object.

Where is parent XPath in Selenium?

We can select the parent element of a known element with Selenium webdriver. First of all we have to identify the known element with the help of any of the locators like id, classname and so on. Then we have to identify its parent element with findElement(By. xpath()) method.

How do I traverse back to parent in XPath?

IN the XPath we can traverse backward using the double dots(..). We can traverse backward as many levels as we want like ../../… For example, if we want to find the parent of any child div selector then we can use it as.


1 Answers

You could to do:

//input[@name='q' and ancestor-or-self::*[@name='f']]
// -- input element whose name='q' and who has an ancestor with the name='f'

or

//input[@name='q' and ../../../../../../*[@name='f']]
// -- input element whose name='q' and who is 5 parents up with the name='f'

You can use this desktop XPath Visualizer to test your XPath expressions. A basic tutorial can be found here.

like image 96
Rubens Farias Avatar answered Nov 03 '22 21:11

Rubens Farias