Preface
If you are new to XPath, the power and flexibility of XPath can be a bit bewildering. This page contains some examples to get you started. After that, I recommend the XPath resources linked on our Types of Element Locators page.
“raw” XPath
To find the link in this page:
- <html><body>
- <p>The fox jumped over the lazy brown <a href="dogs.html">dog</a>.</p>
- </body></html>
Child of Element ID
XPath can find an element by ID like this:
So if you need to find an element that is near another element with an ID, like the link in this example:
- <html><body>
- <p id="fox">The fox jumped over the lazy brown <a href="dogs.html">dog</a>.</p>
- </body></html>
Button Text
There are two ways to declare a standard button in HTML, discounting the many ways to make something that looks like a button, but is not. To determine how an element is declared in the HTML, see how to inspect an element in the browser. If the button is declared with the <button> tag and the button says “press me”, try this:
If the button is a form submit button (declared with the <input> tag and type=”submit” or =”button”) and says “press me”, try this:
Text of element
Sometimes a bit of text is styled as a link or button. To find it, try this:
The Nth element
To find the Nth element, you must surround your XPath in ()s and then specify the Nth using [n], like this:
A very simple example – find the 3rd link on a page:
To find the 4rd text input field on a page:
You can also traverse from the indexed element. So, to find the link in the 2nd div with class ‘abc’:
Supplement
* W3C XPath evalutation online
沒有留言:
張貼留言