8 - First Selenium Webdriver Script
8 - First Selenium Webdriver Script
Example
Using the Java class "myclass" that we created in the previous tutorial, let us try to
create a WebDriver script that would:
WebDriver Code
Below is the actual WebDriver code for the logic presented by the scenario above
Note: Starting Firefox 35, you need to use gecko driver created by Mozilla for
Web Driver. Also, if the code does not work, downgrade to Firefox version 47
or below. Gecko has compatibility issues with recent versions of Firefox.
package newproject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PG1 {
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.
For convenience, we saved the Base URL and the expected title as variables.
Here is a sample code that locates an element by its id. Facebook is used as the
Base URL.
package newproject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
driver.get(baseUrl);
tagName = driver.findElement(By.id("email")).getTagName();
System.out.println(tagName);
driver.close();
System.exit(0);
}
}
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.
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.
Get Commands
Get commands fetch various important information about the page/element. Here
are some important "get" commands you must be familiar with.
get() Sample usage: 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.
getText() Sample usage: Fetches the inner text of the element that you specify
Navigate commands
These commands allow you to refresh,go-into and switch back and forth between
different web pages.
navigate().to() Sample usage: 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.
Notice that only the parent browser window was closed and not the two pop-up
windows.
But if you use quit(), all windows will be closed - not just the parent one. Try running
the code below and you will notice that the two pop-ups above will automatically be
closed as well.
package newproject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
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.
package newproject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PG4 {
public static void main(String[] args) {
System.setProperty("webdriver.firefox.marionette","C:\\gecko
driver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/selenium/deprecated.html");
driver.switchTo().frame("classFrame");
driver.findElement(By.linkText("Deprecated")).click();
driver.close();
}
}
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.
First, head over to http://jsbin.com/usidix/1 and manually click the "Go!" button there
and see for yourself the message text.
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
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:
Waits
There are two kinds of waits.
1. Implicit wait - used to set the default waiting time throughout the program
2. Explicit wait - used to set the waiting time for a particular instance only
Implicit Wait
It is simpler to code than Explicit Waits.
It is usually declared in the instantiation part of the code.
You will only need one additional package to import.
To start using an implicit wait, you would have to import this package into your code.
Explicit Wait
Explicit waits are done using the WebDriverWait and ExpectedCondition
classes. For the following example, we shall wait up to 10 seconds for an element
whose id is "username" to become visible before proceeding to the next command.
Here are the steps.
Step 1
Step 2
Use myWaitVar with ExpectedConditions on portions where you need the explicit
wait to occur. In this case, we will use explicit wait on the "username" (Mercury
Tours HomePage) input before we type the text "tutorial" onto it.
Conditions
Following methods are used in conditional and looping operations --
isSelected() is used when you want to verify whether a certain check box,
radio button, or option in a drop-down box is selected. It does not work on
other elements.
Using ExpectedConditions
The ExpectedConditions class offers a wider set of conditions that you can use in
conjunction with WebDriverWait's until() method.
Catching Exceptions
When using isEnabled(), isDisplayed(), and isSelected(), WebDriver assumes that
the element already exists on the page. Otherwise, it will throw
a NoSuchElementException. To avoid this, we should use a try-catch block so that
the program will not be interrupted.
catch(NoSuchElementException nsee){
System.out.println(nsee.toString());
}
If you use explicit waits, the type of exception that you should catch is the
"TimeoutException".
Summary
To start using the WebDriver API, you must import at least these two
packages.
org.openqa.selenium.*
org.openqa.selenium.firefox.FirefoxDriver
The get() method is the equivalent of Selenium IDE's "open" command.
Locating elements in WebDriver is done by using
the findElementBy() method.
The following are the available options for locating elements in WebDriver:
By.className
By.cssSelector
By.id
By.linkText
By.name
By.partialLinkText
By.tagName
By.xpath
TheBy.cssSelector() does not support the "contains" feature.
You can instantiate an element using the WebElement class.
Clicking on an element is done by using the click() method.
WebDriver provides these useful get commands:
get()
getTitle()
getPageSource()
getCurrentUrl()
getText()
WebDriver provides these useful navigation commands
navigate().forward()
navigate().back()
navigate().to()
navigate().refresh()
The close() and quit() methods are used to close browser windows. Close() is
used to close a single window; while quit() is used to close all windows
associated to the parent window that the WebDriver object was controlling.
The switchTo().frame() and switchTo().alert() methods are used to direct
WebDriver's focus onto a frame or alert, respectively.
Implicit waits are used to set the waiting time throughout the program,
while explicit waits are used only on specific portions.
You can use the isEnabled(), isDisplayed(),isSelected(), and a combination
of WebDriverWait and ExpectedConditions methods when verifying the
state of an element. However, they do not verify if the element exists.
When isEnabled(), isDisplayed(),or isSelected() was called while the element
was not existing, WebDriver will throw a NoSuchElementException.
When WebDriverWait and ExpectedConditions methods were called while the
element was not existing, WebDriver would throw a TimeoutException.