XPath Power

XPath support is indispensable for any serious web test automation tool because xpath expressions allow to precisely select nearly everything in an HTML page using a concise syntax.

Last week I had again a case showing the power of XPath. Colleagues had to write a WebTest script that should (among other steps) change the value of a select like this one:

<select name="mySelect">
<option value=""></option>
<option value="1">English</option>
<option value="2">French</option>
<option value="3">German</option>

(this blog doesn’t allow to “display” this select field it as it would normally appear, but you have surely enough HTML knowledge to understand it)

No assumption could be made on the current value of the select, the test had just to select an other valid option (meaning not the first one).

First approach
The first approach could be to read the index of the selected option, increment it, perform a modulo operation and avoid the first option. More pragmatic would be to take the second one (here “English”) if it is not already selected and the 3rd one (here “French”) if “English” was selected.
These solutions work but require some logic that can only be expressed in a script.

More elegant solution with xpath
In fact you can simply formulate the test specification with an XPath like this one:

//select[@name='mySelect']/option[text() and . != ../option[@selected]]

This XPath just selects all the options of select field mySelect that have a “content” (i.e. not the first, empty one) and that are not currently selected.

NB: WebTest’s setSelectField step takes automatically the first option when the xpath evaluation returns more than one result. For other test tools, you may need to select explicitly the first option like this (//select[@name='mySelect']/option[text() and . != ../option[@selected]])[1]



  1. Swetha said,

    March 5, 2008 at 3:53 pm


    i have to implement a webtest which requires to store more than one value from xpath.
    we are using canoo and i have a requirement like i have to retrieve all the labels in the html. using xpath i may get all the labels but through canoo how can i store all the labels
    i tried using storeXpath and it is just stroing the first anchored element
    can you please tell me a way to store all the labels returned by xpath in the canoo.


  2. Marc Guillemot said,

    March 5, 2008 at 4:37 pm

    Swetha, please use WebTest mailing list for such a question.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: