Selenium Element locator and jQuery

Selenium Element locator and jQuery

In previous post we learned about Selenium IDE installation and its record and playback functionalities. When we were recording the test, we recorded script in table form with column; Command-Target-Value. Today we will try to understand these fields in detail and especially Target field as this is the most important component of web testing. We will actually identify the element to which we are going to access or test.

First we will discuss about these fields:

Command: As name explained itself, command is the action performed inside web browser during testing of application like click, clickAndWait, verify etc..

Target: Unique Address or identifier like id, value or other HTML property of web element.

Value: Send or retrieve any text or value to or from the web browser.

Now we will take a fairly simple example to understand all three columns.

Goal: Type string ‘xyz’ in a textbox and Press Go button on home page of www.seleniumhq.org.

Step1: Identify command to perform type.

Step2: Find the address of the element where you are going to type.

Step3: Send string ‘xyz’ to the textbox using command identified at step1.

step4: find unique identifier for the Go button

Step5: Identify command to perform ‘clicks’.

Step6: Send command identified at step 5 to Go button.

REMEMBER: Selenium command names are same as behavior. To do click we have command “click”. To do typing we have “type”.

As above mentioned, we are done with step1 and step5.

Open www.seleniumhq.org. Open Firebug and active the option ‘Click an element in the page to inspect’ on the firebug. Hover the mouse to desired textbox. As a result of hover, the element will highlight in browser. Click to the element. Complete HTML code for that element will highlight in firebug and you can copy element with properties if you want. you can see code : <input id=”q” type=”text” size=”30″ accesskey=”s” name=”q”> highlighted. You can use id=”q” as the unique id on the page to identify the textbox.

Repeat same steps to identify unique address for Go button. It will be <input id=”submit” type=”submit” value=”Go”>. Use id=”submit” as a unique identifier.

Now you fill the table with above given commands.

Command

Target

Value

type

id=”q”

xyz

click

id=”submit”

Do lot of practice with IDE to record script, create script, execute that, debug that. I am sure, you will notice some locator are bit complicated to understand for some people specially who don’t have enough experience in HTML coding.. If you feel that locator are getting complex to understand like css=blah blah, div#blah, div.blahblah etc. Don’t you worry. In later paragraphs we will try to simplify the search of locator in most easiest way. For now just concentrate for some important commands.

If you have done through practice with IDE then I am sure you have been familiar with multiple selenium commands. Today will talk about some basic commands of selenium which we are going to use most frequently in our test framework other than click (), type () etc. I would recommend you to go through these commands thoroughly and try to practice them in IDE.

We will now record some events and try to understand if there are other way to represent the locator.

Case #1:

Open, www.cnn.com and at home page, highlight the Logo “CNN” on top of the screen. You will see the following code. The value of attribute may change in future but the format will be the same.

 <a id="hdr-banner-title" href="/">
     <img width="119" height="82" border="0" alt="CNN" src="http://i.cdn.turner.com/cnn/.e/img/3.0/global/header/hdr-main.gif">
 </a> 

If you see above code u can see that element is ‘img’ and attributes are as CSS[Cascade Style Sheet].

So you can write the locator to perform any action like click on logo as css=webElement[attributeName=”value”].

In this case we can write as

css=img[alt=”CNN], OR

css=img[src=”http://i.cdn.turner.com/cnn/.e/img/3.0/global/header/hdr-main.gif”].

Just make sure that you are choosing the attribute and value which is unique on that page.

Command

Target

Value

clickAndWait

css=img[alt=”CNN”]

OR

clickAndWait

css=img[src=”http://i.cdn.turner.com/cnn/.e/img/3.0/global/header/hdr-main.gif”]

Case #2:

Open http://developer.android.com/index.html and in home you can see a section ‘News’ in middle of the page. At the right side of page you can see android download section with image

If you try to read the code using firebug, it would be something like this

<tr>
    <td class="imageCell">
        <a href="/sdk/index.html">
         <img style="padding: 0pt; background-color: transparent;" src="/assets/images/icon_download.jpg"> {}
        </a>
    </td>
    <td>
        <h2 class="green">Download</h2>
         <p>The Android SDK has the tools, sample code, and docs you need to create great apps.</p>
         <p>
         <a href="/sdk/index.html">Learn more »</a>
         </p>
    </td>
</tr>

If you go more into html code you will see that all section on right side is divided into table with multiple rows and one each row divided into two columns. First column contains image and second column with some text. Above code is part of one row on that section. Now we want to click on the image. With first column td with class=”imageCell” contains android logo image. To click the image we could use css=image[src=”/assets/images/icon_download.jpg”] as we have discussed in case 1 but this will not work as you cannot see the full address of the source in html code so if you try even like css=image[src=”http://developer.android.com/assets/images/icon_download.jpg”] but if you try to locate this image using IDE, it will not highlight as HTML code will not match with the link.

[error] locator not found: css=image[src=”/assets/images/icon_download.jpg”]

 [error] locator not found: css=image[src="http://developer.android.com/assets/images/icon_download.jpg"]

I this case we need to find some other way to locate. For that we need to study the code. If you spend some time to read the code inside the right side of the body were the code is, you will see a pattern which making this image bit different than others.

If you look at the code you will see a pattern. To click icon_marekt.jpg you can use css=a[href=” http://market.android.com/publish“] and you will be able to highlight too. But in the case where we want to click, similar method will again not work as there is no full link of the link there. There is a little possibility that other element in this section also have the same pattern as this one. I found the fourth row of Target Device also has the similar pattern. In such scenario concept of Xpath come into picture which gives us the complete path of the element in code beginning from <html> tag. We can get the xpath using firebug. Keep your mouse icon to the <image> element of the target icon of which xpath you want to find. Right click on the mouse you select option copy Xpath. Paste this xPath into Target column with prefix “/” like.

Command

Target

Value

clickAndWait

//html/body/div[2]/div/div/div[2]/table/tbody/tr/td/a/img

Case #3:

In above two cases we learned how to use id/class to locate the element and how to reach to the target element in case of difficulties in finding element using id. In this section we will try to combine both cases where we have id/class name and we want to located element directly.

Go to http://www.apple.com and locate and highlight the store tab on the home page using firebug. you will see the following code.

In case 2, navigation from parent element to child element was using forward slash (‘/‘) but in this case we will use greater than (>) sign.

……..GranparentElement>ParentElement>TargetElement

Let’s try to understand this concept using above code from apple website. you will see that all <li> element as different id. we can use css=li[id=”gn-store”] as discussed in last case. Incase if we have class attribute the we can write as as css=li[class=”Blah Blah”] but this time we will try to find if there is other way to do that. Selenium facilitate us to use id and class in short form. We can use following syntax to write locator.

For ID, use #:         For above case we can write locator as :     css= #webElement or css=webElement#id

For Class, use dot (.):     If you have class instead of id then write locator as: css=.webElement or css = element.classname

Thus, to click on Store tab we will write locator as:

css=li#gn-store > a > span OR

css=#gn-store > a > span

Try with IDE to click and I am sure you will be able to click from home page. If you try to click after going to store page, you will not be able to do as the code again changed after click. In that case you have to write diffent line based on changed code. This can be good self-practice test for you to write code to click on store tab.

We have discussed all there very common cases to find locator. First case is the most stable way to locate the web element but that is in ideal scenarios if you have process oriented project where it’s compulsory for developers to write id for each element on web page. but in most scenarios you will not find this. Most of website are not using id for every element. In such cases we need to locate web elements either by class or by xpath but again both are dynamic. We are in dynamic world where requirement can change anytime. That can cause change in css file or addition/removal of any web element on page that may cause failure of our script because of unknown locator. We cannot afford this as cost of re-writing script is not cheap.

At this point we need to think of some other way to search for web element which is independent of any changes in web page except changes in element itself. We can use power of jQuery to do this in very easy format. Nowadays millions of websites are using jQuery code in their webpage to while development. If your application is not using jQuery then can embed small jQuery script in page using selenium and perform greedy search for element in most easy and stable format.

There is a selenium command, AddLocationStrategy, which is available in Selenium RC but not in IDE. We will learn how to use this while designing framework in later post but for now we will just try to understand the basic concept of jQuery first.

jQuery:

jQuery is free, open source software, dual-licensed under the MIT License or the GNU General Public License, jQuery is written in the form which make life easy for us to navigate into document select various elements etc.

The bold text in above line is more important to us. We will use this feature to search locator for the target element. I will give couple of examples to make is more clear.

jQuery Syntax:

The jQuery syntax is tailor made for selecting HTML elements and performs some action on the element(s).

Basic syntax is: $(selector).action()

  • A dollar sign to define jQuery

  • A (selector) to “query (or find)” HTML elements

  • A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() – hides current element

$(“p”).hide() – hides all paragraphs

$(“p.test”).hide() – hides all paragraphs with class=”test”

$(“#test”).hide() – hides the element with id=”test”

I highlighted the selector with red. This selector is the one we need to learn for locating element. We will concentrate on selectors in detail now.

jQuery Selectors:

jQuery selectors allow you to select HTML elements (or groups of elements) by element name, attribute name or by content.

Query Element Selectors jQuery Attribute Selectors
jQuery uses CSS selectors to select HTML elements.

$(“p”) selects all <p> elements.

$(“p.second”) selects all <p> elements with class=” second “.

$(“textbox#sample”) selects all <textbox> elements with id=” sample”.

jQuery uses XPath expressions to select elements with given attributes.

$(“[href]”) select all elements with an href attribute.

$(“[href=’xyz’]”) select all elements with an href value equal to “xyz”.

$(“[href!=’ xyz ‘]”) select all elements with an href attribute NOT equal to ” xyz”.

$(“[href$=’.jpg’]”) select all elements with an href attribute that ends with “.jpg”.

$(“[href^=’fuel-input-‘]”) select all elements with an href attribute that starts with “fuel-input-“.

$(“p”) selects all <p> elements.

$(“p.second”) selects all <p> elements with class=” second “.

$(“textbox#sample”) selects all <textbox> elements with id=” sample”.jQuery uses XPath expressions to select elements with given attributes.

$(“[href]”) select all elements with an href attribute.

$(“[href=’xyz’]”) select all elements with an href value equal to “xyz”.

$(“[href!=’ xyz ‘]”) select all elements with an href attribute NOT equal to ” xyz”.

$(“[href$=’.jpg’]”) select all elements with an href attribute that ends with “.jpg”.

$(“[href^=’fuel-input-‘]”) select all elements with an href attribute that starts with “fuel-input-“.

We will be using jQuery Attribute selector more frequently in out script as it will be make our job more easy. So again I would recommend you to learn basic of jQuery selector from jQuery Tutorial1 and Tutorial2. Don’t spend more time on that but at least one day to be confident enough. Don’t forget to bookmark those links as you may need them to search for special case and that will help your specially Tutorial2.

After adding jQuery and a strategy name ‘jquery’ into selenium we will be able to access element in very easy manner. Following code will be used in place of our first example used in test.

selenium.type(“jquery=input[id=’q’]”,”xyz”);

selenium.click(“jquery=button[id=’buttonId’]”);

But we will discuss about Selenium commands and how to add jquery in selenium in detail in next post. Please go through jQuery tutorial for basic. Don’t go in very detail as we don’t need to be an expert in jQuery to do testing in selenium.

Please write me if you find anything incorrect or if you have anything which is not clear yet. I will try to make it clear.




7 Comments

  1. Sushma

    I would appreciate if you can explain the flow of what to use when. Could you also please give more explanation on how to use SelectFrame (locator):,fireEvent (locator, eventName):and AddLocationStrategy(StrategyName, Strategy):, commands with examples. And also, could you explain when do we use jQuery with an example.

    1. Sushma,
      Thanks for you valuable comments
      We updated the post. We removed command section for now and updated this post with more ways to locate the web elements and then explained about jQuery. In later post we will discuss about commands where we will explain all important commands in more detail with examples.

      Thanks,
      [email protected]

  2. Balji

    Thanks for the post , currently i am working on the application having Mega menu option . mouse over events. For which i am seeking how to use JQuery in selenium. U have posted that in next post u will tell how to use jquery in selenium. It will be help full if u explain with some example related to mouse over event.

  3. Hi guys, thanks for such valuable information.

    I’m currently looking to develop a kind of accelerator for my framework to cut down my work on Object repository. I would really appreciate if you can help me with the object identification done by selenium IDE at the time of recording & playback.

    I’m basically interested in knowing how they create absolute or relative xpaths.

    Thanks in advance 🙂

Leave a Reply