Selenium
Selenium
#selenium
Table of Contents
About 1
Remarks 2
Versions 2
Examples 3
Examples 7
C# Extensions to WebDriver 7
Java 7
Introduction 9
Examples 9
Setting up ChromeDriver 11
Remarks 14
Examples 15
Examples 16
Android + Chrome + Python 16
Examples 17
Remarks 18
Examples 18
Simple Selenium-NUnit 18
Examples 20
Simple page load test and make sure the title of the page is correct 20
Examples 21
C# TakeScreenshot extension 21
Introduction 23
Examples 23
Examples 25
WebDriver Factory C# 25
Chapter 12: WebDriverManager for Selenium - a very neat tool from Boni Garcia 27
Introduction 27
Examples 27
Credits 28
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: selenium
It is an unofficial and free selenium ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official selenium.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with selenium
Remarks
Selenium is a powerful library of commands in multiple languages (C#, Haskell, Java, JavaScript,
Objective-C, Perl, PHP, Python, R, and Ruby) that allow a programmer to automate browser
interaction. This is incredibly useful for developers testing applications.
Selenium runs in webdrivers, which are similar to a normal web browser but allow Selenium to
interact with them. A Selenium test typically opens up a new driver instance of whatever browser
the developer is testing in, which is always a clean slate. This way, when running a Selenium test,
the developer does not have to worry about previous cookies, or a browser cache affecting the
results of their application.
Versions
3.4.0 2017-04-11
3.3 2017-04-07
3.2 2017-02-27
3.1 2017-02-13
3.0.1 2016-11-19
3.0 2016-10-11
https://riptutorial.com/ 2
Examples
Simple Selenium test in Java
Below code is simple java program using selenium. The journey of the below code is
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
// An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time
// when trying to find an element or elements if they are not immediately available.
// The default setting is 0. Once set, the implicit wait is set for the life of the
WebDriver object instance.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Visit Google
driver.get("http://www.google.com");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
https://riptutorial.com/ 3
Simple selenium test in python
# Go to www.google.com
driver.get("https://www.google.com")
The easiest way is to use pip and VirtualEnv. Selenium also requires python 3.*.
$: cd my_selenium_project
$: source venv/bin/active
You should see now see (venv) at the beginning of each bash line. Install Selenium using pip:
https://riptutorial.com/ 4
$: pip install chromedriver
You now have a version-controlled VirtualEnv. To make sure everything is set up correctly:
Start python:
$: python
Prints out:
>>> driver.quit()
>>> quit()
$: deactivate
• Make sure you also have the chrome browser installed. If you don't, the Selenium
chromedriver can not access the Chrome binary.
• webdriver.Chrome() can also take a parameter for your chromedriver location. If you
installed it using pip, try (on mac) driver =
webdriver.Chrome("./venv/selenium/webdriver/chromedriver").
//Navigate to www.google.com
driver.Navigate().GoToUrl("https://www.google.com");
https://riptutorial.com/ 5
//Submit the input
element.Submit();
https://riptutorial.com/ 6
Chapter 2: Accepting popup alerts with
Selenium
Examples
Python example of Accepting alert
C# Extensions to WebDriver
How to use:
driver.acceptAlert();
driver.dismissAlert();
Java
https://riptutorial.com/ 7
String alertText = simpleAlert.getText();
System.out.println("Alert text is " + alertText);
simpleAlert.accept();
Another way you can do this, is wrap your code inside a try-catch:
try{
// Your logic here.
} catch(UnhandledAlertException e){
Alert alert = driver.switchTo().alert();
alert.accept();
}
// Continue.
https://riptutorial.com/ 8
Chapter 3: First project in selenium with Java
Introduction
This is an introduction to Selenium, using Java. While we don't expect you to know anything
regarding Selenium, you have to have prior Java knowledge to follow this course.
Download Links :
Selenium
IntelliJ IDEA
ChromeDriver
JDK 8
Examples
Setting up IntelliJ Idea for Selenium
Prerequisites:
1. Java is installed
2. Selenium is extracted in a folder (Contains 2 files, and 1 folder)
https://riptutorial.com/ 9
Now, go to
There, click on the green plus(+) icon, and choose Library. Then navigate to the extracted
Selenium folder, and add "selenium-java 2.4.0.jar". After adding this, click on the green plus(+)
icon again, and now choose "Directory". This time, locate the libs folder of Selenium, and click on
ok, while selecting it.
https://riptutorial.com/ 10
Now, click on OK, and you're all set.
Setting up ChromeDriver
https://riptutorial.com/ 11
Opening up a Website using Selenium
We use the get method to go to a website. For Example, this would open google
Every Html-Element in Selenium is called a WebElement. For example, a p tag would be a WebElement
, an a tag would be a WebElement, etc. Consider the following html Structure:
link.click();
Lets take another example. If we wanted the text of the p tag, ie, "This is a paragraph", we can do
WebElement p = driver.findElement(By.className("p1"));
System.out.println(p.getText());
Now that we know the basics of Selenium, we can make our own project. For this example, we'll
be making a program, which finds the Newest questions on stack-overflow.
https://riptutorial.com/ 12
System.setProperty("webdriver.chrome.driver", "path of the exe file\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https:stackoverflow.com");
Thread.sleep(3000);
driver.quit();
}
Now, if you look at the source of the page, you find that all questions, are a tags, with an
className of question-hyperlink. However, since there are multiple questions, we use a List of
WebElement, instead of WebElement. Thus, we can do
Now, we need to get the href attribute of the a tag, which has the link of the question. To do this,
we can use getAttribute("href") on the each WebElement, like
To get the attribute of a WebElement, we use getAttribute on that WebElement. For example, consider
the following html tag
WebElement e = driver.findElement(By.id("click"));
System.out.println(e.getAttribute("href")); //prints https://www.google.com
https://riptutorial.com/ 13
Chapter 4: Getting started with Selenium in
python
Remarks
What is Selenium?
Selenium is a library of commands to help a programmer interface with a browser like a real user.
"method" represents any of the above methods to find an element or list of elements.
• click function:
○ driver.find_element_by_method.click()
• send_keys function:
https://riptutorial.com/ 14
Examples
Basic python Selenium
This is a basic example of a Selenium testcase using the python Unittest library
class SeleniumTest(Unittest.testcase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(30)
def test(self):
self.driver.get("https//www.google.com")
self.driver.find_element_by_id("lst-ib").send_keys("python")
self.driver.find_element_by_css_selector("span[class=\"sbico\"]").click()
def tearDown(self):
self.driver.quit()
https://riptutorial.com/ 15
Chapter 5: Mobile app automation
Examples
Android + Chrome + Python
To be able to work with web-application on Android device using Selenium below pre-conditions
should be met:
Start adb and chromedriver server with below commands from cmd/Terminal:
adb start-server
chromedriver
Note down chromedriver server port number from log that looks like
capabilities = {
'chromeOptions': {
'androidPackage': 'com.android.chrome',
}
}
driver = webdriver.Remote('http://localhost:9515', capabilities) # Specify your port number
value
driver.get('http://google.com')
driver.quit()
https://riptutorial.com/ 16
Chapter 6: Selenium IDE
Examples
Try a simple Selenium script: Search Wikipedia on Google
Prerequisites:
• Install Firefox
• Install Selenium IDE addon (https://addons.mozilla.org/fr/firefox/addon/selenium-ide/)
Open the plugin. A button displaying a red circle must be shown. If it's pressed, it means you can
start your scenario. The plugin is recording everything you do within this Firefox instance.
Do whatever you want to be recorded.
In the end, save your scenario; you will notice that Selenium IDE's scenarios are html files.
You can also open files from other users. For instance, copy and paste the code below in a new
html file and import it via your plugin. You will be able to run the -very simple- scenario.
https://riptutorial.com/ 17
Chapter 7: Selenium simple example C# and
Nunit
Remarks
This is a very basic example or starting Selenium, accessing and using a page and then shutting
down Selenium within NUnit.
Examples
Simple Selenium-NUnit
Prereqs:
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using System;
[TestFixture]
public class GoToGoogle
{
//The WebDriver object
IWebDriver driver;
//Ran before test cases
[TestFixtureSetUp]
public void setup()
{
//Initialize the webdriver
//An example of IE
driver = new InternetExplorerDriver();
//Firefox Example
//driver = new FirefoxDriver();
//An example of Chrome
//driver = new ChromeDriver();
https://riptutorial.com/ 18
//going to google.com
driver.Navigate().GoToUrl("www.google.com");
//Assert we are on google.com
Assert.AreEqual(driver.Title, "Google");
//Getting the search field
IWebElement searchField = driver.FindElement(By.Name("q"));
//Typing in the search field
searchField.SendKeys("Selenium Tutorial");
//Submitting
searchField.Submit();
https://riptutorial.com/ 19
Chapter 8: Selenium simple example C# and
Nunit
Examples
Simple page load test and make sure the title of the page is correct
[SetUp]
public void LoadDriver()
{
_driver = new ChromeDriver();
[Test]
public void Valid_Home_Page_Title()
{
_driver.Navigate().GoToUrl("Your homeoage url / local or remote");
StringAssert.Contains("Expected title of your page", _driver.Title);
[TearDown]
public void UnloadDriver()
{
_driver.Quit();
}
}
https://riptutorial.com/ 20
Chapter 9: Take a screenshot of a webpage
Examples
Python Selenium take/save screenshot of webpage
driver.save_screenshot will return 'true' if the screenshot was taken, and 'false' if it was not. Saving
screenshots also works with headless browsers. If you want to save a screenshot in a different
directory, just add the filepath (relative to where you are running the code from). For example:
screenshot_name = "screenshots/my_screenshot_name.png"
Will save the screenshot in directory "screenshots" inside the directory that python is being run
from.
C# TakeScreenshot extension
Usage example:
driver.TakeScreenshot().SaveAsFile(@"/Test/Test.png",ImageFormat.Png);
Alternately
https://riptutorial.com/ 21
public static void captureScreenShot(WebDriver ldriver){
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
https://riptutorial.com/ 22
Chapter 10: Waiting in Selenium
Introduction
One of the most common stumbling blocks for newer Selenium users is waiting until a page is fully
loaded. Human users can easily tell if a page has fully loaded or if it is still loading. Selenium,
however, just waits for a set amount of time. Therefore, it is often convenient to have a good way
to wait for elements in a page. While it is possible to do this with a loop and sleep() functions,
there are much cleaner ways already built into Selenium.
Examples
Explicit Wait in Python
When browser navigates to a dynamic page (most commonly AJAX-based web application), the
elements on the page can take different time to load, and furthermore: some elements will only
load in response to some user actions. In such cases direct retrieval of an element may fail:
The most obvious solution it seems to introduce the wait before retrieving elements:
But such solution is inefficient, since it causes the test to always wait for 5 seconds, even when
the element in most cases appears after 1 second (and only sometimes requires up to 5 seconds).
It doesn't look much if it's one place, but usually each test deals with multiple elements, and there
are multiple tests, which adds up to overall test duration.
A better solution is to wait for element to appear for up to 5 seconds, but return from the wait as
soon as element is found. WebDriverWait allows you to do just that.
The following example navigates to www.google.com, waits (for up to 5 seconds) for the search
bar to load, and then searches for "selenium".
https://riptutorial.com/ 23
# Go to www.google.com
driver.get("https://www.google.com")
try:
# Wait as long as required, or maximum of 5 sec for element to appear
# If successful, retrieves the element
element = WebDriverWait(driver,5).until(
EC.presence_of_element_located((By.NAME, "q")))
# Type "selenium"
element.send_keys("selenium")
#Type Enter
element.send_keys(Keys.ENTER)
except TimeoutException:
print("Failed to load search bar at www.google.com")
finally:
driver.quit()
Explicit wait : Wait for a certain condition to occur before proceeding further in the code.
Implicit wait: Wait for a certain amount of time when trying to find an element or elements if they
are not immediately available.
https://riptutorial.com/ 24
Chapter 11: WebDriver Factory
Examples
WebDriver Factory C#
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
/// <summary>
/// Factory for creating WebDriver for various browsers.
/// </summary>
public static class WebDriverFactory
{
/// <summary>
/// Initilizes IWebDriver base on the given WebBrowser name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static IWebDriver CreateWebDriver(WebBrowser name)
{
switch (name)
{
case WebBrowser.Firefox:
return new FirefoxDriver();
case WebBrowser.IE:
case WebBrowser.InternetExplorer:
InternetExplorerOptions ieOption = new InternetExplorerOptions();
ieOption.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
ieOption.EnsureCleanSession = true;
ieOption.RequireWindowFocus = true;
return new InternetExplorerDriver(@"./", ieOption);
case "safari":
return new RemoteWebDriver(new Uri("http://mac-ip-address:the-opened-port"),
DesiredCapabilities.Safari());
case WebBrowser.Chrome:
default:
ChromeOptions chromeOption = new ChromeOptions();
string location = @"./";
chromeOption.AddArguments("--disable-extensions");
return new ChromeDriver(location, chromeOption);
}
}
}
https://riptutorial.com/ 25
// Usage
var driver = WebDriverFactory.CreateWebDriver(WebBrowser.Chrome);
https://riptutorial.com/ 26
Chapter 12: WebDriverManager for Selenium
- a very neat tool from Boni Garcia
Introduction
I switched to Selenium 3 and started using Chrome instead of Firefox. I discovered that for
Chrome I need to download a binary for WebDriver to handle the browser. For that to work I need
to set absolute path to this binary as Java variable. If binary gets updated, I need to update that
binary manually in my test framework - which takes time and is really annoying. I discovered a
very neat Java library that does it for me: https://github.com/bonigarcia/webdrivermanager
Examples
Below examples shows how easy it is to use
ChromeDriverManager.getInstance().setup();
FirefoxDriverManager.getInstance().setup();
OperaDriverManager.getInstance().setup();
PhantomJsDriverManager.getInstance().setup();
EdgeDriverManager.getInstance().setup();
InternetExplorerDriverManager.getInstance().setup();
Read WebDriverManager for Selenium - a very neat tool from Boni Garcia online:
https://riptutorial.com/selenium/topic/10582/webdrivermanager-for-selenium---a-very-neat-tool-
from-boni-garcia
https://riptutorial.com/ 27
Credits
S.
Chapters Contributors
No
Getting started with akhilsk, Alex.K., Brydenr, Community, Eugene S, Priya, Pseudo
1
selenium Sudo, Ruslan López Carro, Thomas, Venkatesh Achanta
Accepting popup
2 Brydenr, Paul Muir, Priya, slackmart
alerts with Selenium
First project in
3 Frank Underwood
selenium with Java
Mobile app
5 Andersson
automation
Selenium simple
7 example C# and Paul Muir
Nunit
Take a screenshot of
8 Brydenr, DuarteNGF, Paul Muir, Priya
a webpage
9 Waiting in Selenium Brydenr, John Fisher, Kiril S., Priya, Pseudo Sudo
WebDriverManager
for Selenium - a very
11 sen4ik
neat tool from Boni
Garcia
https://riptutorial.com/ 28