WATIR allows you to access elements based on pre-defined attributes. But there are some cases where a simple watir method cannot be used. Cases such as below:

Case 1 – > There is an element that cannot be accessed using pre-defined attributes

Case 2 -> There is no API for a particular HTML element

Case 3-> Access an element based on some other element.

In all the above cases, we can use XPath to access such elements. WATIR has a new attribute to address such elements called, “:xpath”. The use of xpath in above cases is illustrated below:

1 – > There is an element that cannot be accessed using pre-defined attributes. The figure below shows a text box and its DOM properties.

As seen in the DOM, ‘ignoreesc’ is not a standard attribute. So, inorder to validate that the textbox exists, we can use the following xpath query:

2 – > There is no API for a particular HTML element i.e., there is no class in WATIR:

Take an example of a map element. Now for “map” element there is no class in WATIR that can be used to access the elements. Here, you can use the function “element_by_xpath” .

The DOM of a map is shown below:

< map name=”top_menu_map” id=”top_menu_map”>
< area shape=”rect” coords=”18,2,62,17″ ref=”http://engin.com.au/public/index.htm” target=”_self” alt=”engin home”> < /area >
< /map>

Now you want to access “area” element. You can do it using the function described above. So to access element the statement will look like:

3 -> Access an element based on some other element.

Suppose you need to access an element(which doesn’t have any fix attribute) based on position of some other element(which has a fix attribute). WATIR doesn’t provide any direct way to access element based on position of other element. So what you can do is Go to the element which is fixed using WATiR classes. Then, traverse the DOM tree using the underlying “ole_object” for that element . The below figure shows a drop down box and its DOM.



Now suppose you want to access the drop down. You can use the following xpath query.

 

More information about xpath can be found in the following sites:

Enhanced by Zemanta