XPath gets
quiet a bad press with regards to Selenium testing, and is sometimes the reason
people ‘give up’ with their test automation. Basically, XPath is very powerful,
it treats the web page as a structured document (which it is), and allows you
to traverse the hierarchy of nodes (elements).
The two
common misconceptions of XPath are: it’s slow, and it’s brittle. These are only
true of complex XPaths that are heavily dependent of the structure of your web
page. It’s true that in general XPath is slower than CSS locators, but you can
just as easily write complex and brittle CSS locators.
XPath is one
of the locator strategies often used when Selenium IDE is recording a test. The
brittleness and speed issues can be mostly avoided by using simple and relative
XPaths. This means finding an element near the one you want that you can locate
quickly and easily (great if it has an id), and then describing how to get to
your target element. As with CSS, some examples will help me to explain.
<div
id="register">
<label>Email:</label>
<input
type="text"/>
<label>Full
Name:</label>
<input
type="text"/>
</div>
To locate
the fullname textbox in the above HTML snippet you could use the following:
xpath=id(‘register’)/input[2]
This locates
the second input element beneath the element with an id value of ‘register’
xpath=//label[text()=‘Full
Name:’]/following-sibling::input
This first
locates a label element with the text contents of ‘Full Name:’ and then moves
onto the following input element
The more
complex your XPath gets, the longer it could take for the browser to find your
element, and the more dependent your locator is on the structure of the page.
This means that minor changes to the HTML on the page that cause no functional
changes could quite easily cause your tests to fail.
No comments:
Post a Comment