Sie sind auf Seite 1von 23

Introduction to Selenium

by Andrew Thompson

Lab 1.0.

URL http://www.bbc.co.uk
File BBC-BASIC-001.html
Objective(s) To introduce the record and playback features.
To make use of the basic IDE functionality.
Understand how assert and validate commands are created.

Tutors Notes

This is a gentle introduction to Selenium. Use the BBC home page and get the delegates to
record some actions – navigating to the technology page for instance.
Introduce the basic features of the IDE – saving, setting breakpoints, start points, copying and
pasting commands and inserting basic commands to verify what has happened,
This will also introduce how to manually create actions – in particular validations and
assertions. Explain the difference the two and ensure all delegates have created both types.

Delegate Instructions

From Firefox open the Selenium IDE. Tools -> Selenium IDE. Ensure the record button is
depressed – it should be as default.
Next go to the BBC home page and navigate to news main page and then the technology
section. Here select something from the Tech Lab – bottom of the page. Stop recording and
save the test – File->Save As.

You should now have 4 selenium commands (1 open, 2 clicks and 1 select) that correspond to
the 4 actions that have been recorded in your test.

(Duration 5 minutes)

[Presentation 1. Selenese Fitnesse command structure – command, locators and values]

(Duration 10 minutes)

Next copy these 4 commands and paste them directly below the original set. Rerun the test.
Now add a breakpoint at the first action that clicks on the technology link – right click on the
action for this selenium option. Rerun the test to the breakpoint. Take off breakpoint.
Select a different start point for your test – the 2nd open action would be a good choice, but
feel free to experiment. Setting start points is another right click option available. Rerun your
test.

(Duration 10-20 minutes)

[Presentation 2. Selenium IDE – walkthrough the features of the selenium IDE]

(Duration 10 minutes)

Now add some basic validation around the title of the last page you have selected, e.g. “The
Tech Lab: Gordon Frazer” title. Using the IDE there are 2 ways of manually enhancing your
tests with additional commands.
Firstly: after highlighting the text in the web browser, right click your mouse and you will get
some options on what commands are available to you. If you select “Show all available
commands” you will be given further options. Certainly not all, as we will soon see. Next back
in your IDE session right click to insert one last command. This is the second way of building
commands outside of just recording your activity.

Once you have selected “Insert New Command”, the IDE will create an empty command line
for you to use. Click into that line. You should have something similar to the screenshot above.
The Command, Target and Value fields should be empty. Create a verify command first. Click
on the command drop down and you will see the complete command set available to you.
You can filter the list by entering the first letter of the command you wish to create – v in our
case. Now create a new command for assertion. Finally rerun your test. Can you see how
Selenium uses the two types of commands to perform two different types of validation? Edit
the value of your tests – so that they fail and this will become clearer. There is no need to
rerun your test with the play button. Double clicking any command in the IDE will run that
command in isolation.
As assertions and validations have to be explicitly created these methods of manually creating
actions are worth remembering.
Reminder: save your test before continuing.
(Duration 10 – 15 minutes)

Lab 1.2.

URL http://www.w3schools.com/xpath/default.asp
File Locators.html
Objective(s)
To provide a basic understanding of how Selenium uses and records locators, in
particular XPATH, element id and name locators.

Introduce Firebug.

Tutors Notes
Which locators are recorded will depend upon which actions have been used and how the
AUT has been designed and implemented. For instance, if the web documents have been
created with strict adherence the W3C standards your options on which locator you can use
and what gets recorded will be far richer and clearer.
The use of locators is a vast subject and to fully understand it requires a thorough
understanding of how web documents are structured and formed by web browsers and the
web application. However, we need to ensure that delegates have some understanding on
what they are recording. Generally this will mean understanding the XPATH and element id
of the HTML.

Delegate Instructions

Understanding Locators in critical to fully understanding Selenium and probably any other
web tool that tests within the browser.
After opening the w3schools URL, create a command to validate the title page – do not use
one of the TextPresent commands. Next enter something in the search box – top right hand
side – do not search for it. You should end up with something like the screen shot below:

Or expressed in Selenese:

assertText //h1 XPath Tutorial


type as_q XPATH tutorial
assertValue as_q XPATH tutorial

It’s the locator – the bit under the target column - that we are going to focus on. We have
recorded two distinct types of locators – an XPATH and name locator. There are a few more
1will help us understand how Selenium has indentified these within the web document.

Right click within your browser and select inspect element. Firebug will open in an iFrame at
the bottom web browser. Select “Inspect” and click on the title. Ensure you get something
like the screenshot below before you continue. Firebug will display the HTML of the web
document and highlight the element within that structure that you have selected for
inspection. You will get something like:
<h1>XPath Tutorial</h1>

It should now be a little clearer why Selenium has recorded //h1, for this elements location.
The “//” is just an XPATHs expression – in this case saying find this anywhere within the web
document or DOM.

Next use Firebug to inspect the second element you have recorded – the search box.
The html for this element is something like:

<input type="text" size="20" name="as_q" style="width: 90px;" alt="search"/>

Selenium has used the name locator to identifier this element within the DOM.
There are of course standards around the naming of attributes for HTML and the way HTML
elements are indentified. Selenium supports those which are recognised by the major
browsers.
The name attribute is a common one. Another one to be aware of is the id attribute. The
W3Schools site doesn’t seem to keen on using the id attribute. As it is important to see it
action and if we can become more comfortable with Firebug we will create one in a moment.
(Duration 15 – 20 minutes)
In general, Selenium will record what it thinks is the most useful locator for a particular
element. This will depend on the type of element in question, but will usually be in the
following order: id, name, XPATH.
So in our demo, if the id attribute was available we would probably expect Selenium to have
recorded that instead of the name.
Selenium is fairly robust in finding these elements and doesn’t itself explicitly record the
locator type it is using – we have just “as_q” rather than “name=as_q”. But these are seen as
one and the same by Selenium.
To see this, create the explicit version in your test. Ensure you run it to make sure it really is
OK.
There’s another way you can ensure it’s valid and Selenium can locate it. That’s to make use of
the “Find” button on the IDE. It should highlight the element – in green – if it can find it!

Whatever Selenium records, you can of course override this selection with your own locator,
based on your own location strategy. There are reasons why you may wish to do this and this
is discussed later – under locator strategies.

For now let’s create a new attribute using Firebug. Inspect the element you are interested in-
the search box for instance. Within the HTML tab of Firebug rightclick your mouse and you
will see the “New Atribute”. Create an ”id” attribute and give it any value you wish – I have
given mine the value of “lab”.

Now that this new attribute exists you will be able to reference it using a new type of locator
for identifying this element. Again you may explicitly identify this type of locator or not.
Selenium appears to be able to indentify it – so long as it’s a unique reference within the
DOM.

Your test should now look like something like the following:
Run your entire test to make sure all is well.

Selenium has very rich functionality in this area, which gives you great scope in building
automation scripts for very different web applications.
(Duration 10 – 15 minutes)

Lab 1.2.

URL http://www.w3schools.com/js/tryit.asp?filename=tryjs_checkbox
File DHTML-001-UpperCase.html
Objective(s) To give a basic demo of DHTML and highlight it’s difference from AJAX.

To appreciate how web page content and structure can change without page
loads.
To appreciate how the the HTML can change based on user driven events. This
does have implications on validating through Selenium.

To appreciate how DHTML is based on Javascript. and make use of Web Developer
tool.

Tutors Notes

It is easy to mistake highly functional DHTML and AJAX. Their behaviour is often very similar
in terms of the user experience.
The main reason to demo this is to make the differentiation between DHTML and the AJAX
that follows.
The are additional tasks which involve Web Developer and Firebug.

Delegate Instructions

Enter you first name and surname and record through SIDE- do not convert to uppercase yet.
Insert some Selenium commands to verify your data entry. Then run your test.
Now convert to uppercase using the selection. Make sure the record button is depressed.
Copy your verifications to the end of your script and re-run your test. Make any necessary
corrections to your verifications and re-run the test again.

Next make use of Web Developer to disable all Javascript (right click – Web Developer ->
Disable -> Disable Javascript-> All Javascript). Re-run the exercise.
Reverse the action when finished.

Additional exercise:

Edit the JS function convertToUcase to the following – changing the lname to fname in the
second command.

function convertToUcase()
{
document.getElementById("fname").value=document.getElementById("fname").value.to
UpperCase();
document.getElementById("lname").value=document.getElementById("fname").value.to
UpperCase();
}

Click the “Edit the text and click me” button. Manually click the convert radio button to
observe the affect this has had.
Now try and find your new JavaScript code in Firebug – via the script tab.

Next rerun the Selenium test – do not start from the first line of your script – as this will load
the original page and overwrite your new JS. Instead use the SIDE feature of creating an
alternative start point. Right the command you wish to start from and you should have the
option.

(Duration 5 -15 minutes)

Lab 2.1.

URL http://www.w3schools.com/ajax/ajax_xmlfile.asp
File AJAX-04-RESPONSE-HTML.html
Objective(s) To appreciate how Selenium handles AJAX html responses.
Some of Selenium location strategies and modifiers to them.
Making use of Firebug.

Tutors Notes

The delegates will record the selection of various customers. The server-side asp will provide a
piece of HTML – a single HTML element. The client-side JS has been written to use
xmlHttp.responseText and the HTTP response will be a string.
This presents issues of locating particular targets amongst a single bit of text. Modifiers to
standard location strategies may have to be used.

Delegate Instructions
Record a couple of selections and try to validate the results. In particular validate the selected
Artists country of origin.
Make use of Firebug (right click – inspect element) to see AJAX in action and its affect on the
HTML and DOM.

(Duration 10-20 minutes)

Lab 2..2

URL http://www.w3schools.com/ajax/ajax_responsexml.asp
File AJAX-05-RESPONSE-XML.html
Objective(s) To appreciate how Selenium handles AJAX xml responses and what affect this can
have on the dynamic html values.
Making use of the waitFor* command set.
Making use of Firebug.

Tutors Notes

The delegate will record the selection of various customers. The server-side asp will provide a
piece of XML that has a consistent structure but values based on the customer selection.
This should enable the delegate to appreciate the different uses of the waitFor commands. In
particular waitForElementPresent and waitForValue. As the resulting XML does not change its
structure the latter command is not particularly useful in this case.

Delegate Instructions

Record a couple of selections and try to validate the results.


Make use of Firebug (right click – inspect element) to see AJAX in action and its affect on the
HTML and DOM.

(Duration 10-20 minutes)

Lab 2.3.

URL http://www.w3schools.com/xpath/default.asp
File Locators.html
Objective(s)

Tutors Notes

We will now return to locators. Delegates need to see all locators in action, look at their use in
more depth and introduce locator strategies.
This is just not important in understanding the scope of locators, but this does have a very
practical benefit when applications do not have “standard” locators or when the locators
change.

It’s also important to discuss some of the vulnerabilities and issues of using some locators over
others. There is a presentation on location strategies that will cover this is more detail.
Discuss other locators, such as XQUERY and SPAQL. Ask delegates for any others they may
know and whether they are included as Selenium locators

Delegate Instructions

This next lab takes you further into how Selenium builds it’s target data and provides you with
the full scope of its locator strategies. Available should you need them. Although this lab is
not optional, delegates should not see this lab as fundamental to them being able to use
Selenium. Generally speaking the target locators you get out of the box are generally fine – so
if you fail to fully grasp this next lab do not despair! However, most delegates will appreciate
being able to troubleshoot and re-write original test recordings.

You can use your earlier locator.html file or the on referenced here if you prefer – it in the
finishing state of the html from the previous lab.

Firstly let’s look at the XPATH locator. Looking at the first example we created can you suggest
any vulnerabilities such a test definition may have?
Let’s use Firebug to change the text in the HTML, we will just change the text. Before you re-
run your original test what do you think will happen when you do so?

Fortunately, Selenium has some flexibility in the way you express locators and modify their
values.
We’ll now go through some examples of how you can use regular expression to modify what
might be unnecessarily strict validations. N.B. that these expressions can be used for all
location strategies.

LINK Locator and more XPATH


The Link locator is perhaps the least versatile locator, but it’s very simple to understand and
what you normally get when you record any clicks on links. When you do, you will end up
with something like the following:

clickAndWait link=XPath HOME

However, as links are HTML we can fall back on more XPATH expressions if we need to.

DOM
The DOM locator allows you to use the power of Javascript and build expressions to traverse
your HTML. How much you can exploit this option will depend upon how comfortable you
feel writing Javascript.

Some more examples using Links.

clickAndWait dom=document.links[3]
The javascript expression – the bit after the “dom=”, locators the 4th link in the DOM. The DOM
can be complex, but Firebug can reveal some of its secrets. Click on the Dom tab and locate
the document node. When you expand this, further nodes are revealed including the links
node.

There are of course other nodes within the document node, that you can also reference
through your Javascript expressions.

For instance the image node:


clickAndWait dom=document.images[3]

Take a look at the information contain within the DOM and write a few other actions based
around the images and links nodes. What is available to you will, of course depend on how
the web document has been designed – which is probably out of your control.

There are two more locator types that we can look at - CSS and ID. They are used in a very
similar way as the Name locator is used, but for completeness delegate should look at them if
they get the time.

[Presentation 3. Selenium IDE – locator strategies]

Lab 2.4– (Optional).

URL http://www.csszengarden.com/
File css_locator-001.html
Objective(s)

Tutors Notes

For completeness and to piggyback a few other tasks this lab is worthwhile. It demonstrates
the explicit use of the css selector.
Although this site presents little challenge to automation – it is static and in a very good state
compliance wise – it does offer great insight into CSS and how selenium can make reference
to its’ elements.

Delegate Instructions

The final selector is through the web documents CSS. Open the Zen Garden link above.
Under “select a design”, choose the Kelmscott design. Use Firebug to inspect the text starting
“A demonstration of what can be accomplished..” – near the top.

The screenshot above shows where you should be. Now use Web Developer to display the
CSS on this page. Right click -> Web Developer -> CSS -> View CSS. This will give you a new tab
with full details of all the CSS definitions available, including any active on the HTML we are
interested in. The quickSummary and its p1 class are abstracted below.

#quickSummary {

clear: both;

margin: 20px 20px 20px 10px;

width: 160px;

float: left;

#quickSummary p {

font: italic 1.1em/2.2 georgia;

text-align: center;

We can use Selenium to refer to HTML elements via explicit reference to the web page CSS.
For instance:
assertText css=p[class="p1"] A demonstrate*

Or even using the id of the HTML:

assertText css=div[id="quickSummary"] A demonstrate*

Finally, navigate through the designs. Run your Selenium script each time to check on the
validity of your commands.
Although OpenQA does have a growing interest in the presentation layer, generally speaking
it is focused on functionality. For instance - one thing to note about the Selenium tests above
is that both assertions are against the DOM and not what is visually displayed via the CSS.

Lab 3.0

URL http://www.tallyhouniforms.com/
File Prog-001.html
Objective(s)
Introduce manual scripting via the IDE. And Firebug.

Understanding some of the basic concepts of Selenium programming through the


IDE.

Introduce declaration and use of variables within Selenium scripts.

Tutors Notes

Delegates should now feel fairly comfortable working with Selenium and ready for a more
intense lab experience.
Demo the Prog-001.html and the run through the how variables get declared and how they
can get used within the scripts.
As its W3C compliance is very loose, the Tallyho site presents a rich set of challenges for
automation, including dynamic ids and names for elements.

Delegate Instructions

Run the prog001 script to see what it does.


Now we will use the Selenese code in prog001, to write some more test scripts – without the
record feature of SIDE.
Using only your knowledge of Selenium create the following:

Open the http://www.tallyhouniforms.com site – order some items – based on a predefined


variable and proceed to checkout. Provide email and password information as required. Use
as much predefined variables as you can and reuse – again using variables - any data entries
you make. Step through your code (IDE -> Step button-> Play-> Step ) and make sure it all
works as you planned. Remember to use Firebug if you are having trouble identifying
elements.

Modify your script so that you do not proceed to check out, but instead continue shopping.
Again try and do this manually. Rerun your script a few times to see you order increase in size.
Next put a break point on your script to review your basket. Do you really need all that stuff?
Insert a command to delete some of your order. Either execute your command in situ (double
click on it) or rerun the entire script.
Now rewrite the script so that each time it runs it deletes the oldest item in your shopping cart
– the one at the top of the list.

The shopping basket view presents the automated script with challenges if we wish to refer to
items on it.
Let’s consider the issue of deleting an item. Out of the box the IDE will record something like
the following:

click del1202184124309

Checking the HTML – via Firebug – we see something like:

<input type="image" style="border-width: 0px;"


src="http://www.tallyhouniforms.com/images/jac6/jac6delet1.gif"
id="del1202184124309” name="del1202184124309"/>

The application is clearly using dynamically generated values for its ids and names. This breaks
a W3C standard - but is pretty common. The value we record in our script is good for one run
at best – if we keep the static value that is.

Now, enhance the code you have written to get around this issue. There are several ways you
could do this, just ensure it works!

So to recap – the script should build a shopping basket containing an order of several items.
The shopper should be allowed to continue shopping, but have no more than 3 different
items in their basket – deletes should be made on the shopping basket view to the oldest item
– the topmost.

Next create a new variable for the total order price. Rewrite your script so that it keeps a
running total of your order and validate it against the subtotal of the shopping basket. You
may wish to vary your order to make this task a bit more demanding.
Additional task
The TallyHo site is a ideal to showcase one of the very many great features of Web Developer.
Right click and go to Web Developer -> Tools -> Validate HTML, is does not matter which view
you chose. See if you can identify any issues mentioned in the report. The report on the
shopping basket view is given below.

Lab 3.1

URL http:// www.bbc.co.uk /


File Prog-003.html

Introduce user extensions.


Objective(s)

Tutors Notes

Selenium RC offers you the Selenium API for major programming languages. So if you require
a high degree of programmability this would be achieved via Java, Perl or C# etc., not
through Javascript User Extensions. Javascript has by design, limitations to what you can do
with it that the aforementioned do not - for instance direct database interactivity.

However, for entirely web based programmability Javascript is by design exceptionally useful.
Even, if the intention of delegates is to implement Selenium RC and it probably is, the
Selenium User Extensions offer an invaluable insight to how Selenium works. This is hardly
surprisingly, as Selenium is essentially based on Javascript. It is also implemented in a very
similar way as the User Extensions are. Furthermore, most User Extensions can be
implemented via Selenium RC and developing Javascript and an RC supported language is a
strong option.
Note on difference in User Extensions
User Extension are broken into two groups those written for the playback using the IDE and
TestRunner or playback using TestRunner only. The main reason why Extensions do not
support the IDE playback is that some have been written assuming the existence of a test
suite. This is fine by TestRunner but not the IDE. The IDE sees only one test script at a time.

For extensions that will not work through the IDE you usually get something like: “selenium
IDE users Note: In selenium IDE you won't be able to play your script in the editing window
but you will be able to play them in selenium TestRunner.”

Delegate Instructions

One way to extend the functionality of Selenium is via User Extensions. They are written in
Javascript and designed to be integrated into Selenium. It’s a testimony to the activity of the
Selenium development community. Many of them get incorporated into the main releases or
just offer specialist functionality.

We are going to download two that will help us extend Seleniums programming capabilities
through the IDE.

Lab 3.2

URL http:// www.airmiles.co.uk /


File Prog-006.html

Considering more basic concepts of Selenium programming through the IDE.


Objective(s)

Tutors Notes

Delegate Instructions

Before we going any further tick the “Record assertTitle automatically” under Selenium IDE–>
Options -> Options -> General tab. This feature is either an annoyance or quite useful
depending on how meaningful the HTML title has been made. Anyway turn it on for now.
Now go to the Airmiles site and book a flight from Gatwick to Barcelona. We want to travel
out on the 19th September and return on the 21st September. Take all the defaults about
people and travel times and continue all the way to the Hotel availability page.
You should end with a Selenium script looking something like the following screenshot:
Now playback the script.
When the script is played back it has a few failures – in red in the screenshot below. Put a
breakpoint on the action – on failure and just before. Replay your script.
It should be clear from the playback that the default wait time on clickAndWait is not
sufficient for the page load. Although we can increase this time we should consider waiting
for an event instead of a set time period. Indeed the “wait” command is not the most reliable
unless we have fast page loads or very consistent performance. Fortunately, we have a range
of “waitFor” commands to assist. The “waitForTitle” is good in this case, but feel free to chose
your own. Replace the clickAndWait with click and assertTitle on NULL (which is erroneous
due to the lack of a page during recording) with a new waitFor command based on the
AIRMILES title. So you’ll have the following:

Click //input[@value='Search']
waitForTitle AIRMILES

Rerun your script. Things should be a bit better this time. Depending on the speed of the site
at this particular time you may need an addition waitFor commands, before clicking through
to the hotel page. At the time of writing I have needed to add the following and since the
response times are unreliable its probably a good idea to add it anyway.
waitForElementPresent getFlightsImg

Now remove any breakpoints and run your script again. When using the debugger with
breakpoints always ensure after you have debugged any issue successfully that you do a final
run without breakpoints. This will, of course ensure it work as planned during an automated
run. Debugger can is some circumstances stop this from happening.

Note on the debugger and waits:

If your script is having problems with waits and timeouts, then be careful using breakpoints to
troubleshoot the issue. As the script will pause at the breakpoint it may well allow enough
time for a page load to be successful. Thus making it impossible to reproduce the problem you
are having with timeouts. If you suspect this then increase the default timeout (through your
IDE options and for the temporary period of debugging) or use waitFor commands, without
breakpoints.
Now we can get down to the lab work:
After sorting the hotel selection by price, write a script that will always choose the cheapest
hotel and proceed to the payment options.

Additional task

Had enough with this? If not push your script a little further and incorporate the following:
Enhance your script so that it verifies that the prices you get actually agree with the original
ones that were presented to you when you selected the hotel.
Further enhance your script so that the travel arrangements you made are accurately
displayed – at least in terms of dates and airports

Dealing with Dynamic Outcomes

Consider the robustness of this script over time. There are some obvious implications for some
of the test data involved in our recording.
Make tests at least self consistent or introduce some means of using expected results.

Lab 3.2

URL http:// www.airmiles.co.uk /


File Prog-007.html

Introduce User Extensions


Objective(s)
Installing User Extensions and using them. Understanding how they work and
reading the JavaScript involved.

Tutors Notes

Delegates Notes

User Extensions

Now let us look at a very powerful way of extending the functionality of the IDE command
set. We will look at one with some relevance to the current lab.
Consider the ordering of our search results by cash.

clickAndWait Cash

We should have something like the command above – the locator on this site is very helpful.
However, often they are not and often you may prefer to specify your test we a greater
reference to a requirement as opposed to the implementation. So in other words specify
something like:

clickAndWait Cash price

There are many reasons why we would want to write our tests in this way. Remember in the
original case the locator is a HTML element – it is not what the user experiences. If there is a
defect in this area, for instance the HTML elements and text get mixed – then our tests may
not pick this up.
Having a test based on selecting the “Cash price” text is closer to the user story and closer to
the business requirement.

http://wiki.openqa.org/display/SEL/locateByLabelText

The locateByLabelText user extension is written in Javascript (like all other Selenium User
Extensions) and gives as a new location strategy based on the label element

Now go to the link above and download the extensions – save it to an area on your harddrive
– remember where.

Now we can reference the extension through the Selenium IDE.

For this new user extension to be available in the IDE we need to restart the IDE. The
documentation related to the extension will tell you how to use it. Most concern creating new
actions – which will then be available through the IDE command selection.
clickAndWait labelText=Cash price

We should end with something like the command above. Although, this is far more verbose
that the original - it is a much better test specification.

User extensions – apart from the very specialise ones – tend to get promoted into the main
release of the Selenium IDE. So bear this in mind should your favourite one just disappear
from the user extension area one day.

As mentioned this user extension is written in Javascript. Which can present a great
opportunity to extend and customise Selenium IDE in away that suits you and the AUT.

Deciding between Selenium IDE/Core and RC:

http://wiki.openqa.org/pages/viewpage.action?pageId=422

Das könnte Ihnen auch gefallen