Selenium IDE - viva college

SELENIUM
What is SELENIUM?
• Selenium is a free (open source) automated testing suite for web
applications across different browsers and platforms.
• Selenium is not just a single tool but a suite of software, each catering
to different testing needs of an organization. It has four components.
•
•
•
•
Selenium Integrated Development Environment (IDE)
Selenium Remote Control (RC)
WebDriver
Selenium Grid
SELENIUM IDE
• Selenium Integrated Development Environment (IDE)
is the simplest framework in the Selenium suite and
is the easiest one to learn. It is a Firefox plugin that
you can install as easily as you can with other plugins.
However, because of its simplicity, Selenium IDE
should only be used as a prototyping tool.
• If you want to create more advanced test cases, you
will need to use either Selenium RC or WebDriver.
SELENIUM REMOTE CONTROL (RC)
• Selenium RC was the flagship testing framework of the whole Selenium
project for a long time. This is the first automated web testing tool
that allowed users to use a programming language they prefer. As of, RC
can support the following programming languages:
• Java
• C#
• PHP
• Python
• Perl
• Ruby
SELENIUM WEB DRIVER
• The WebDriver proves itself to be better than both Selenium IDE and Selenium
RC in many aspects. It implements a more modern and stable approach in
automating the browser’s actions. WebDriver, unlike Selenium RC, does not rely
on JavaScript for automation. It controls the browser by directly communicating
to it.
• The supported languages are the same as those in Selenium RC.
• Java
• C#
• PHP
• Python
• Perl
• Ruby
SELENIUM GRID
• Selenium Grid is a tool used together with Selenium RC to run
parallel tests across different machines and different browsers all at
the same time. Parallel execution means running multiple tests at
once.
• Features:
• Enables simultaneous running of tests in multiple browsers and
environments.
• Saves time enormously.
• Utilizes the hub-and-nodes concept. The hub acts as a central source of
Selenium commands to each node connected to it.
Selenium IDE
Selenium RC
WebDriver
Internet Explorer versions 6 to 9, both 32 and 64-bit
Firefox 3.0, 3.5, 3.6, 4.0, 5.0, 6, 7 and above
(current version is 16.0.1)
Browser
Support
Mozilla Firefox
Mozilla Firefox
Internet Explorer
Google Chrome
Safari
Opera
Konqueror
Others
Google Chrome 12.0.712.0 and above
(current version is 22.0.1229.94 m)
Opera 11.5 and above
(current version is 12.02)
Android – 2.3 and above for phones and tablets
(devices & emulators)
iOS 3+ for phones (devices & emulators) and 3.2+ for tablets (devices & emulators)
HtmlUnit 2.9 and above
(current version is 2.10)
Operating System
Windows
Mac OS X
Linux
Windows
Mac OS X
Linux
Solaris
All operating systems where the browsers above can run.
Tool
Why Choose ?
Selenium IDE
•To learn about concepts on automated testing and Selenium, including:
•Selenese commands such as type, open, clickAndWait, assert, verify, etc.
•Locators such as id, name, xpath, css selector, etc.
•Executing customized JavaScript code using runScript
•Exporting test cases in various formats.
•To create tests with little or no prior knowledge in programming.
•To create simple test cases and test suites that you can export later to RC or WebDriver.
•To test a web application against Firefox only.
Selenium RC
•To design a test using a more expressive language than Selenese
•To run your test against different browsers (except HtmlUnit) on different operating systems.
•To deploy your tests across multiple environments using Selenium Grid.
•To test your application against a new browser that supports JavaScript.
•To test web applications with complex AJAX-based scenarios.
WebDriver
Selenium Grid
•To use a certain programming language in designing your test case.
•To test applications that are rich in AJAX-based functionalities.
•To execute tests on the HtmlUnit browser.
•To create customized test results.
•To run your Selenium RC scripts in multiple browsers and operating systems simultaneously.
•To run a huge test suite, that need to complete in soonest time possible.
Create a Script by Recording
Step 1
•Launch Firefox and Selenium IDE.
•Type the value for our Base URL: http://newtours.demoaut.com/.
•Toggle the Record button on (if it is not yet toggled on by default).
Step 2
• In Firefox, navigate to http://newtours.demoaut.com/. Firefox should
take you to the page similar to the one shown below.
Step 3
• Right-click on any blank space within the page, like on the Mercury Tours logo on the upper left corner. This
will bring up the Selenium IDE context menu. Note: Do not click on any hyperlinked objects or images
• Select the “Show Available Commands” option.
• Then, select “assertTitle exact:Welcome: Mercury Tours”. This is a command that makes sure that the page
title is correct.
Step 3
Step 4
•In the “User Name” text box of Mercury Tours, type an invalid username, “invalidUN”.
•In the “Password” text box, type an invalid password, “invalidPW”.
Step 5
• Click on the “Sign-In” button. Firefox should take you to this page.
Step 6
• Toggle the record button off to stop recording. Your script should now
look like the one shown below.
Step 7
• Now that we are done with our test script, we shall save it in a test
case. In the File menu, select “Save Test Case”. Alternatively, you can
simply press Ctrl+S.
Step 8
• Choose your desired location, and then name the test case as
“Invalid_login”.
• Click the “Save” button.
Step 9
• Notice that the file was saved as HTML.
Step 10
• Go back to Selenium IDE and click the Playback button to execute the
whole script. Selenium IDE should be able to replicate everything
flawlessly.
Selenium Commands
• Introduction to Selenium Commands – Selenese
• Selenese commands can have up to a maximum of two parameters:
target and value.
• Parameters are not required all the time. It depends on how many the
command will need.
3 types of commands
Actions
Accessors
Assertions
These are commands that directly interact with page elements.
Example: the “click” command is an action because you directly interact with the element you are clicking at.
The “type” command is also an action because you are putting values into a text box, and the text box shows
them to you in return. There is a two-way interaction between you and the text box.
They are commands that allow you to store values to a variable.
Example: the “storeTitle” command is an accessor because it only “reads” the page title and saves it in a
variable. It does not interact with any element on the page.
They are commands that verify if a certain condition is met.
3 Types of Assertions
•Assert. When an “assert” command fails, the test is stopped immediately.
•Verify. When a “verify” command fails, Selenium IDE logs this failure and continues with the test execution.
•WaitFor. Before proceeding to the next command, “waitFor” commands will first wait for a certain condition
to become true.
• If the condition becomes true within the waiting period, the step passes.
• If the condition does not become true, the step fails. Failure is logged, and test execution proceeds to the
next command.
• By default, timeout value is set to 30 seconds. You can change this in the Selenium IDE Options dialog
under the General tab.
ASSERT v/s VERIFY
ASSERT v/s VERIFY
Common Commands
Command
Number of
Parameters
open
0-2
click/clickAndWait
1
Clicks on a specified element.
type/typeKeys
2
Types a sequence of characters.
verifyTitle/assertTitle
1
Compares the actual page title with an expected value.
verifyTextPresent
1
Checks if a certain text is found within the page.
verifyElementPresent
1
Checks the presence of a certain element.
verifyTable
2
Compares the contents of a table with expected
values.
waitForPageToLoad
1
Pauses execution until the page is loaded completely.
waitForElementPresent
1
Pauses execution until the specified element becomes
present.
Description
Opens a page using a URL.
Create a Script Manually with Firebug. Step 1
•Open Firefox and Selenium IDE.
•Type the base URL (http://newtours.demoaut.com/).
•The record button should be OFF.
Step 2
• Click on the topmost blank line in the Editor.
• Type “open” in the Command text box and press Enter.
Step 3:
• Navigate Firefox to our base URL and activate Firebug
• In the Selenium IDE Editor pane, select the second line
(the line below the “open” command) and create the
second command by typing “assertTitle” on the
Command box.
• Feel free to use the autocomplete feature.
Step 4
• In Firebug, expand the <head> tag to display the <title> tag.
• Click on the value of the <title> tag (which is “Welcome: Mercury
Tours”) and paste it onto the Target field in the Editor.
Step 5:
• To create the third command, click on the third
blank line in the Editor and key-in “type” on the
Command text box.
• In Firebug, click on the “Inspect” button.
• Click on the User Name text
box. Notice that Firebug
automatically shows you the
HTML code for that element.
Step 6
• Notice that the User Name text box does not have an ID, but it has a
NAME attribute. We shall, therefore, use its NAME as the locator.
Copy the NAME value and paste it onto the Target field in Selenium
IDE.
Step 6
• Still in the Target text box, prefix “userName” with “name=”,
indicating that Selenium IDE should target an element whose NAME
attribute is “userName.”
Step 6:
• Type “invalidUN” in the Value text box of Selenium IDE. Your test
script should now look like the image below. We are done with the
third command. Note: Instead of invalidUN , you may enter any other
text string. But Selenium IDE is case sensitive and you type
values/attributes exactly like in application.
Step 7
• To create the fourth command, key-in “type” on the Command text
box.
• Again, use Firebug’s “Inspect” button to get the locator for the
“Password” text box.
Step 7
• Paste the NAME attribute (“password”) onto the Target field and
prefix it with “name=”
• Type “invalidPW” in the Value field in Selenium IDE. Your test
script should now look like the image below.
Step 8
• For the fifth command, type “clickAndWait” on the Command text
box in Selenium IDE.
• Use Firebug’s “Inspect” button to get the locator for the “Sign In”
button.
Step 8
Paste the value of the NAME attribute (“login”) onto the Target text
box and prefix it with “name=”.
Your test script should now look like the image below.
Step 9
• Save the test case in the same way as we did in the previous section.
Using Find Button
• The Find button in Selenium IDE is used to verify if what we had put
in the Target text box is indeed the correct UI element.
• Let us use the Invalid_login test case that we created in the previous
sections. Click on any command with a Target entry, say, the third
command.
• Click on the Find button. Notice that the User Name text box within the
Mercury Tours page becomes highlighted for a second.
This indicates that Selenium IDE was able to
detect and access the expected element correctly.
If the Find button highlighted a different element
or no element at all, then there must be
something wrong with your script.
Execute Command
• This allows you to execute any single command without running the
whole test case. Just click on the line you wish to execute and then either
click on “Actions > Execute this command” from the menu bar or simply
press “X” on your keyboard.
• Step 1. Make sure that your browser is on the Mercury Tours homepage.
Click on the command you wish to execute. In this example, click on the
“type | userName | invalidUN” line.
Execute Command
Step 2. Press “X” on your keyboard.
Step 3. Observe that the text box for username becomes populated with the text “invalidUN”
Executing commands this way is highly dependent on the page that Firefox is currently
displaying. This means that if you try the example above with the Google homepage displayed instead
of Mercury Tours’, then your step will fail because there is no text box with a “userName” attribute
within Google’s homepage.
SELENIUM WEBDRIVER
• WebDriver is a web automation framework that allows you to execute your
tests against different browsers, not just Firefox (unlike Selenium IDE).
SELENIUM WEB DRIVER
• WebDriver also enables you to use a programming language in creating your test
scripts(not possible in Selenium IDE).
• You can now use conditional operations like if-then-else or switch-case
• You can also perform looping like do-while.
• Following programming languages are supported by WebDriver
•
•
•
•
•
•
Java
.Net
PHP
Python
Perl
Ruby
• You do not have to know all of them. You just need to be knowledgeable in one.
WebDriver v/s Selenium RC
• Before advent of WebDriver in 2006, there was another, automation
tool called Selenium Remote Control. Both WebDriver and Selenium
RC have following features:
• They both allow you to use a programming language in designing
your test scripts.
• They both allow you to run your tests against different browsers.
ARCHITECTURE
• WebDriver’s architecture is simpler than Selenium RC’s.
• It controls the browser from the OS level
• All you need are your programming language’s IDE (which contains
your Selenium commands) and a browser.
Selenium RC’s architecture is way more
complicated.
• You first need to launch a separate application called Selenium Remote Control (RC)
Server before you can start testing
• The Selenium RC Server acts as a “middleman” between your Selenium commands and your
browser
• When you begin testing, Selenium RC Server “injects” a Javascript program called Selenium
Core into the browser.
• Once injected, Selenium Core will start receiving instructions relayed by the RC Server from your
test program.
• When the instructions are received, Selenium Core will execute them as Javascript commands.
• The browser will obey the instructions of Selenium Core, and will relay its response to the RC
Server.
• The RC Server will receive the response of the browser and then display the results to you.
• RC Server will fetch the next instruction from your test script to repeat the whole cycle.
Speed
• WebDriver is faster than Selenium RC
since it speaks directly to the browser uses
the browser’s own engine to control it.
• Selenium RC is slower sinceit uses a
Javascript program called Selenium
Core.This Selenium Core is the one that
directly controls the browser, not you.
Real-life Interaction
• WebDriver interacts with page elements in a more realistic way. For
example, if you have a disabled text box on a page you were testing,
WebDriver really cannot enter any value in it just as how a real person
cannot.
• Selenium Core, just like other Javascript codes, can access disabled
elements .In the past, Selenium testers complain that Selenium Core was
able to enter values to a disabled text box in their tests.
Differences in API
Selenium RC’s API is more
matured but contains
redundancies and often confusing
commands. For example, most of
the time, testers are confused
whether to use type or typeKeys; or
whether to use click, mouseDown, or
mouseDownAt. Worse, different
browsers interpret each of these
commands in different ways too!
WebDriver’s API is simpler than
Selenium RC’s. It does not contain
redundant and confusing commands.
Browser Support
WebDriver can support the headless HtmlUnit
browser.
HtmlUnit is termed as “headless” because it is an
invisible browser – it is GUI-less.
It is a very fast browser because no time is spent in
waiting for page elements to load. This accelerates your
test execution cycles.
Since it is invisible to the user, it can only be controlled
through automated means.
Selenium RC cannot support the headless
HtmlUnit browser. It needs a real, visible browser to
operate on.
Limitations of WebDriver
• WebDriver Cannot Readily Support New Browsers
• WebDriver operates on the OS level. Also remember that different
browsers communicate with the OS in different ways. If a new
browser comes out, it may have a different process of communicating
with the OS as compared to other browsers.
• However, it is up to the WebDriver’s team of developers to decide if
they should support the new browser or not.
Selenium RC Has Built-In Test Result
Generator
WebDriver v/s Selenium RC
• Selenium RC automatically generates an HTML file of test results.
The format of the report was pre-set by RC itself. Take a look at an
example of this report below.
• WebDriver has no built-in command that automatically generates a
Test Results File. You would have to rely on your IDE’s output window,
or design the report yourself using the capabilities of your
programming language and store it as text, html, etc.
Summary
• WebDriver is a tool for testing web applications across different browsers using
different programming languages.
• You are now able to make powerful tests because WebDriver allows you to use a
programming language of your choice in designing your tests.
• WebDriver is faster than Selenium RC because of its simpler architecture.
• WebDriver directly talks to the browser while Selenium RC needs the help of the
RC Server in order to do so.
• WebDriver’s APIismore concise than Selenium RC’s.
• WebDriver can support HtmlUnit while Selenium RC cannot.
• The only drawbacks of WebDriver are:
• It cannot readily support new browsers, but Selenium RC can.
• It does not have a built-in command for automatic generation of test results.
Installing Selenium WebDriver
• Step 1 – Install Java on your computer
• Step 2 – Install Eclipse IDE
• Step 3 – Download the Selenium Java Client Driver
• Step 4 – Configure Eclipse IDE with WebDriver
Step 4:
1. Launch the “eclipse.exe” file inside the “eclipse” folder that we
extracted in step 2. If you followed step 2 correctly, the executable
should be located on C:\eclipse\eclipse.exe.
2. When asked to select for a workspace, just accept the default
location.
3. Create a new project through File > New > Java Project. Name the
project as “myproject”.
4. Right-click on the newly created project and select New > Package,
and name that package as “mypackage”.
5. Create a new Java class under mypackage by right-clicking on it and
then selecting New > Class, and then name it as “myclass”.
Step 6:
Step 6
1. Right-click on myproject and select Properties.
2. On the Properties dialog, click on “Java Build
Path”.
3. Click on the Libraries tab, and then click “Add
External JARs..”
4. Navigate to C:\selenium-2.25.0\ (or any other
location where you saved the extracted contents
of “selenium-2.25.0.zip” in step 3).
5. Add all the JAR files inside and outside the “libs”
folder.
6. Finally, click OK and we are done importing
Selenium libraries into our project.
WEBDRIVER SCRIPT
Using the Java class “myclass” that we created in the previous tutorial,
let us try to create a WebDriver script that would:
• fetch Mercury Tours’ homepage
• verify its title
• print out the result of the comparison
• close it before ending the entire program.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
package mypackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class myclass {
public static void main(String[] args) {
// declaration and instantiation of objects/variables
WebDriver driver = new FirefoxDriver();
String baseUrl = "http://newtours.demoaut.com";
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = "";
// launch Firefox and direct it to the Base URL
driver.get(baseUrl);
// get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page witht the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
//close Firefox
driver.close();
// exit the program explicitly
System.exit(0);
}
}
Code Explanation
• Importing Packages
• To get started, you need to import following two packages:
• org.openqa.selenium.*- contains the WebDriver class needed to
instantiate a new browser loaded with a specific driver
• org.openqa.selenium.firefox.FirefoxDriver – contains the
FirefoxDriver class needed to instantiate a Firefox-specific driver onto
the browser instantiated by the WebDriver class
• If your test needs more complicated actions such as accessing
another class, taking browser screenshots, or manipulating external
files, definitely you will need to import more packages.
Instantiating objects and variables
Normally, this is how a driver object is instantiated.
A FirefoxDriver class with no parameters means that the
default Firefox profile will be launched by our Java
program. The default Firefox profile is similar to
launching Firefox in safe mode (no extensions are
loaded).
For convenience, we saved the Base URL and the
expected title as variables
Launching a Browser Session
• WebDriver’s get() method is used to launch a new browser session
and directs it to the URL that you specify as its parameter.
Get the Actual Page Title
• The WebDriver class has the getTitle() method that is always used to
obtain the page title of the currently loaded page.
Compare the Expected and Actual Values
This portion of the code simply uses a basic Java if-else structure to compare the actual
title with the expected one.
Terminating a Browser Session
• The “close()” method is used to close the browser window.
Terminating the Entire Program
• If you use this command without closing all browser windows first,
your whole Java program will end, while leaving browser window
open.
Running the Test
• There are two ways to execute code in Eclipse IDE.
• On Eclipse’s menu bar, click Run > Run.
• Press Ctrl+F11 to run the entire code.
If you did everything correctly, Eclipse would
output “Test Passed!”
Locating GUI Elements
• Locating elements in WebDriver is done by using the
“findElement(By.locator())” method. The “locator” part of the code is
same as any of the locators previously discussed in the Selenium IDE
chapters of these tutoriasl.Infact , it is recommeded you locate GUI
elements using IDE and once successfully identified export the code
to webdriver.
• Here is a sample code that locates an element by its id. Facebook is
used as the Base URL.
Locating GUI Elements
1. package mypackage;
2. import org.openqa.selenium.By;
3. import org.openqa.selenium.WebDriver;
4. import org.openqa.selenium.firefox.FirefoxDriver;
5. public class myclass {
6.
public static void main(String[] args) {
7.
WebDriver driver = new FirefoxDriver();
8.
String baseUrl = "http://www.facebook.com";
9.
String tagName = "";
10.
driver.get(baseUrl);
11.
tagName = driver.findElement(By.id("email")).getTagName();
12.
System.out.println(tagName);
13.
driver.close();
14.
System.exit(0);
15.
}
16.}
• We used the getTagName() method to extract the tag name of that
particular element whose id is “email”. When run, this code should be
able to correctly identify the tag name “input” and will print it out on
Eclipse’s Console window.
Some Locating Elements
Variation
Description
By.className
finds elements based on the value of the “class” attribute
By.cssSelector
finds elements based on the driver’s underlying CSS Selector engine
By.id
locates elements by the value of their “id” attribute
Sample
findElement(By.className(“
someClassName”))
findElement(By.cssSelector(“
input#email”))
findElement(By.id(“someId”)
)
finds a link element by the exact text it displays
findElement(By.linkText(“RE
GISTRATION”))
locates elements by the value of the “name” attribute
findElement(By.name(“some
Name”))
By.partialLinkText
locates elements that contain the given link text
findElement(By.partialLinkTe
xt(“REG”))
By.tagName
locates elements by their tag name
By.linkText
By.name
By.xpath
locates elements via XPath
findElement(By.tagName(“di
v”))
findElement(By.xpath(“//ht
ml/body/div/table/tbody/tr/
td[2]/table/tbody/tr[4]/td/t
Note on Using findElement(By.cssSelector())
• By.cssSelector() does not support the “contains” feature. Consider the Selenium IDE code below -
• In Selenium IDE, the entire test passed. However in the WebDriver
script below, the same test generated an error because WebDriver
does not support the “contains” keyword when used in the
By.cssSelector() method.
Common Commands
Instantiating Web Elements
• Instead of using the long “driver.findElement(By.locator())” syntax
every time you will access a particular element, we can instantiate a
WebElement object for it. The WebElement class is contained in the
“org.openqa.selenium.*” package.
Common Commands
Clicking on an Element
• Clicking is perhaps the most common way of interacting with web
elements. The click() method is used to simulate the clicking of any
element. The following example shows how click() was used to click
on Mercury Tours’ “Sign-In” button.
Following things must be noted when using the click() method.
•It does not take any parameter/argument.
•The method automatically waits for a new page to load if applicable.
•The element to be clicked-on, must be visible (height and width must not be equal to
zero).
Get Commands
• Get commands fetch various important information about the
page/element. Here are some important “get” commands you must
be familiar with.
get()
getTitle()
getPageSource()
getCurrentUrl()
getText()
•It automatically opens a new browser window and fetches the page that you specify inside its parentheses.
•It is the counterpart of Selenium IDE’s “open” command.
•The parameter must be a String object.
•Needs no parameters
•Fetches the title of the current page
•Leading and trailing white spaces are trimmed
•Returns a null string if the page has no title
•Needs no parameters
•Returns the source code of the page as a String value
•Needs no parameters
•Fetches the string representing the current URL that the browser is looking at
•Fetches the inner text of the element that you specify
Navigate commands
navigate().to()
navigate().refresh()
navigate().back()
navigate().forward()
•It automatically opens a new browser window and
fetches the page that you specify inside its
parentheses.
•It does exactly the same thing as the get() method.
•Needs no parameters.
•It refreshes the current page.
•Needs no parameters
•Takes you back by one page on the browser’s history.
•Needs no parameters
•Takes you forward by one page on the browser’s
history.
Closing and Quitting Browser Windows
close()
•Needs no parameters
•It closes only the browser window that WebDriver is currently
controlling.
quit()
•Needs no parameters
•It closes all windows that WebDriver has opened.
1. package mypackage;
2. import org.openqa.selenium.WebDriver;
3. import org.openqa.selenium.firefox.FirefoxDriver;
4. public class myclass {
5.
public static void main(String[] args) {
6.
WebDriver driver = new FirefoxDriver();
7.
driver.get("http://www.popuptest.com/popuptest2.html");
8.
driver.quit(); // using QUIT all windows will close
9.
}
10. }
Switching Between Frames
• To access GUI elements in a Frame, we should first direct WebDriver
to focus on the frame or pop-up window first before we can access
elements within them. Let us take, for example, the web
page http://selenium.googlecode.com/svn/trunk/docs/api/java/index
.html
• This page has 3 frames whose “name” attributes are indicated above.
We wish to access the “Deprecated” link encircled above in yellow. In
order to do that, we must first instruct WebDriver to switch to the
“classFrame” frame using the “switchTo().frame()” method. We will
use the name attribute of the frame as the parameter for the
“frame()” part.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class myclass {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://selenium.googlecode.com/svn/trunk/docs/api/java/inde
x.html");
driver.switchTo().frame("classFrame");
driver.findElement(By.linkText("Deprecated")).click();
driver.quit();
}
}
After executing this code, you will see that the “classFrame” frame is taken to the “Deprecated
API” page, meaning that our code was successfully able to access the “Deprecated” link.
Switching Between Pop-up Windows
• WebDriver allows pop-up windows like alerts to be displayed, unlike
in Selenium IDE. To access the elements within the alert (such as the
message it contains), we must use the “switchTo().alert()” method. In
the code below, we will use this method to access the alert box and
then retrieve its message using the “getText()” method, and then
automatically close the alert box using
the“switchTo().alert().accept()” method.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class myclass {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
String alertMessage = "";
driver.get("http://jsbin.com/usidix/1");
driver.findElement(By.cssSelector("input[value=\"Go!\"]")).click();
alertMessage = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alertMessage);
driver.quit();
}
}
On the Eclipse console, notice that the printed
alert message is: