Selenium Key concepts
Browser Navigation Commands
We have four Navigation commands
1. GoToUrl
2. Back
3. Forward
4. Refresh
Navigate to a URL
This Method instructs the selenium WebDriver to navigate to the specified URL.
Command:
Driver.Navigate().GoToUrl(appUrl); // where appUrl is the website address to load.
Example:
Driver.Navigate().GoToUrl(“https://example.com”);
Navigate Backward
This Method simulates the browser’s back button, navigating the WebDriver to the previous page
in the browser history.
Command :
Driver.Navigate().Back(); // This command does not take any parameter.
Navigate Forward
This method simulates the browser’s forward button, navigating the WebDriver to the next page in
the browser history.
Driver.Navigate().Forward(); // This command does not take any parameter.
Refreshing the Page
This method refreshes the current page, similar to pressing the browser’s refresh button.
Driver.Navigate().Refresh(); // This command does not take any parameter.
Maximize and Minimize Commands
Maximize the Window
This command maximizes the current window
Driver.Manage().Window.Maximize(); // This command does not take any parameter.
Minimize the Window
This command minimizes the current window
Driver.Manage().Window.Minimize(); // This command does not take any parameter.
Find Element and Find Elements
FindElement
Finding a single Element: This methods finds and returns the first element that matches the specified
locators(example: ID, Name, Class)
Syntax:
//By ID
IWebElement element = driver.FindElement(By.Id(“elementId”))
//By XPath
IWebElement element = driver.FindElement(By.XPath(“elementXpath”))
FindElements
Finding multiple Elements : This method finds and returns a collection of web elements that match
the specified locator. It returns an empty collection if no elements are found.
Syntax:
ReadOnlyCollection <IWebElement> elements = driver.FindElements(By.Id(“Idname”));
Difference between FindElement & FindElements Commands
The difference between FindElement() and FindElements() method is the first returns a WebElement
object otherwise it throws an exception and the latter returns a List of WebElements, it can return an
empty list if no DOM elements match the query.
FindElement()
On Zero Match : throws NoSuchElementException
On One Match : returns WebElement
On One+ Match : returns the first appearance in DOM
FindElements()
On Zero Match : return an empty list
On One Match : returns list of one WebElement only
On One+ Match : returns list with all matching instance
Locators
Locators in Selenium means something which can identify the Web Elements in Web Application GUI.
Selenium provides us with different types of locators.
1. ID
2. Name
3. Class Name
4. CSS Selector
5. XPath
6. Link Text
7. Partial Link Text
8. Tag Name
ID
To locate a web element using id, we use the attribute value of “id”.
Syntax:
driver. FindElement(By.Id("<<ID of the particular Web Element>>"));
Name
To locate a web element using Name, we use the attribute value of “name”.
Syntax:
driver. FindElement(By.Name("<<Name of the particular Web Element>>"));
ClassName
To locate a web element using ClassName, we use the attribute value of “class”.
Syntax:
driver. FindElement(By.ClassName("<<Class Name of the particular Web Element>>"));
CssSelector
CSS Selector uses pattern to locate the Web element. The CSS Patterns are of different types. The
most commonly used is combination of tag and attribute value
Syntax:
driver.FindElement(By.CssSelector("<<CSS Selector for the particular Web Element>>"));
Example:
driver. FindElement(By.CssSelector("css=input[name=j_username]"));
XPath
To locate a web element using XPath, we use the XPath expression.
Syntax:
driver.FindElement (By.XPath("<<XPath expression for particular Web Element>>"));
LinkText
Link text is generally used to locate web elements of type link. For links, HTML page uses the tag
name called “a”. Sometimes, we may not have any id, name, or classname for the link. In this case,
we are going to locate that link with the help of visble Linktext.
Syntax:
driver.findElement(By.LinkText("<<Link text for the particular Web Element(link)>>"));
PartialLinkText
Partial Link text is also used to locate web elements of type link. Here, we use the some portion
(partial) of the visible link text.
Syntax:
driver.findElement(By.PartialLinkText("<<Partial link text for the particular Web Element(link)
>>"));
TagName
Tag Name locator is used to locate web element using its tag name. Like for Textbox, we use the tag
called “input”. This can be used only when one element is present with the Tag name. Otherwise it
will locate the first available tag in DOM of the page.
Syntax:
driver.findElement(By.TagName("<<Tag name of the particular Web Element >>"));
WebElement Commands
Clear Command
void IWebElement.Clear() - If this element is a text entry element, this will clear the value. This
method accepts nothing as a parameter and returns nothing.
Command
element.Clear();
This method has no effect on other elements. Text entry elements are INPUT and TEXTAREA
elements.
Example :
IWebElement element = driver.FindElement(By.Id("UserName"));
element.Clear();
//Or can be written as
driver.FindElement(By.Id("UserName")).Clear();
SendKeys Command
void IWebElement.SendKeys(string text) - This simulate typing into an element, which may set its
value. This method accepts string as a parameter and returns nothing.
Command
element.SendKeys("text")
This method works fine with text entry elements like INPUT and TEXTAREA elements.
IWebElement element = driver.FindElement(By.Id("UserName"));
element.SendKeys("Text");
//Or can be written as
driver.FindElement(By.Id("UserName")).SendKeys("Text");
Click Command
void IWebElement.Click()- This simulates the clicking of any element. Accepts nothing as a
parameter and returns nothing.
Command
element.Click();
Clicking is perhaps the most common way of interacting with web elements like text elements, links,
radio boxes and many more. There are some preconditions for an element to be clicked. The element
must be Visible and it must have a Height and Width greater than 0.
IWebElement element = driver.FindElement(By.Id("Login"));
element.Click()
//Or can be written as
driver.FindElement(By.Id("Login")).Click()
Displayed Command
bool IWebElement.Displayed{ get; } - This method determines if an element is currently being
displayed or not. This accepts nothing as a parameter but returns Boolean value(true/false).
Command
element.Displayed;
This will return true if the element is present on the page and throw
a NoSuchElementFound exception if the element is not present on the page. This refers to the
property of the element, sometimes the element is present on the page but the property of the
element is set to hidden, in that case, this will return false, as the element is present in the DOM but
not visible to us.
Example:
IWebElement element = driver.FindElement(By.Id("UserName"));
bool status = element.Displayed;
//Or can be written as
bool staus = driver.FindElement(By.Id("UserName")).Displayed;
Enabled Command
bool IWebElement.Enabled{ get; } - This determines if the element currently is Enabled or not? This
accepts nothing as a parameter but returns boolean value(true/false).
Command
element.Enabled;
Example:
IWebElement element = driver.FindElement(By.Id("UserName"));
bool status = element.Enabled;
//Or can be written as
bool staus = driver.FindElement(By.Id("UserName")).Enabled;
Selected Command
bool IWebElement.Selected{ get; } - Determine whether or not this element is selected or not. This
accepts nothing as a parameter but returns boolean value(true/false).
This operation only applies to input elements such as Checkboxes, Select Options and Radio Buttons.
This returns True if the element is currently selected or checked, false otherwise.
Command
element.Selected;
Example:
IWebElement element = driver.FindElement(By.Id("RadioButton"));
bool status = element.Selected;
//Or can be written as
bool staus = driver.FindElement(By.Id("RadioButton")).Selected;
Submit Command
void IWebElement.Submit() - This method works well/better than the Click() if the current element
is a form, or an element within a form. This accepts nothing as a parameter and returns nothing.
Command
element.Submit();
Example
IWebElement element = driver.FindElement(By.Id("SubmitButton"));
element.Submit();
//Or can be written as
driver.FindElement(By.Id("SubmitButton")).Submit();
Text Command
string IWebElement.Text{ get; } - This method will fetch the visible (i.e. not hidden by CSS) innerText
of the element. This accepts nothing as a parameter but returns a String value.
Command
element.Text;
This returns an innerText of the element, including sub-elements, without any leading or trailing
whitespace.
IWebElement element = driver.FindElement(By.Id("example"));
String value = element.Text;
TagName Command
string IWebElement.TagName{ get; } - This method gets the tag name of this element. This accepts
nothing as a parameter and returns a String value.
Command
element.TagName()
This does not return the value of the name attribute but return the tag for e.g. "input" for the
element <input name="foo"/>.
IWebElement element = driver.FindElement(By.Id("SubmitButton"));
String tagName = element.TagName;
//Or can be written as
String tagName = driver.FindElement(By.Id("SubmitButton")).TagName;
GetCssValue Command
string IWebElement.GetCssValue(string propertyName) - This method Fetch CSS property value of
the given element. This accepts string as a parameter which is property name.
Command
element.GetCssValue();
Color values should be returned as rgba strings, so, for example if the "background-color"
property is set as "green" in the HTML source, the returned value will be "rgba(0, 255, 0, 1)".
GetAttribute Command
string IWebElement.GetAttribute(string attributeName) - This method gets the value of the given
attribute of the element. This accepts the String as a parameter and returns a String value.
Command
element.GetAttribute();
Attributes are Ids, Name, Class etc. Using this method you can get the value of the attributes of any
given element.
IWebElement element = driver.FindElement(By.Id("SubmitButton"));
String attValue = element.GetAttribute("id"); //This will return "SubmitButton"
Size Command
System.Drawing.Size IWebElement.Size{ get; } - This method fetch the width and height of the
rendered element. This accepts nothing as a parameter but returns the Dimension object.
Command
element.Size();
This returns the size of the element on the page.
IWebElement element = driver.FindElement(By.Id("SubmitButton"));
Dimension dimensions = element.Size();
Console.WriteLine(“Height :” + dimensions.Height + ”Width : "+ dimensions.Width);
Location Command
System.Drawing.Location IWebElement.Location{ get; } - This method locate the location of the
element on the page. This accepts nothing as a parameter but returns the Point object.
Command
element.Location();
This returns the Point object, from which we can get X and Y coordinates of specific element.
IWebElement element = driver.FindElement(By.Id("SubmitButton"));
Point point = element.Location;
Console.WriteLine("X cordinate : " + point.X + "Y cordinate: " + point.Y);
CheckBox & Radio Button Operations
Checkbox Operations
Selecting Checkbox
IWebElement checkbox = driver.FindElement(By.Id(“checkboxId”));
Checkbox.Click(); //This will select the checkbox
Deselecting Checkbox
IWebElement checkbox = driver.FindElement(By.Id(“checkboxId”));
If(checkbox.Selected) //This will check whether checkbox is selected or not
Checkbox.Click(); //This will De-select the checkbox
Radiobutton Operations
Selecting a RadioButton
IWebElement radiobutton = driver.FindElement(By.Id(“radiobuttonId”));
radiobutton.Click();
Checking if Radiobutton is selected
IWebElement radiobutton = driver.FindElement(By.Id(“radiobuttonId”));
If(!radiobutton.Selected)
radiobutton.Click();
How to Handle Popup Box (Alerts)
Alert interface gives us following methods to deal with the alert:
Accept() To accept the alert
.Dismiss() To dismiss the alert
.Text To get the text of the alert
.SendKeys() To write some text to the alert
Note: Common Exception in this Alert Handling is NoAlertPresentException:
This popup is handled as below
IAlert simpleAlert = driver.SwitchTo().Alert();
String alertText = simpleAlert.Text;
Console.WriteLine("Alert text is " + alertText);
simpleAlert.Accept();
Where
simpleAlert.Accept(); = > Press the 'Leave Page' Button
simpleAlert.Dismiss(); = > Press the 'Stay on Page' Button
How to Handle Windows
string currentWindow = driver.CurrentWindowHandle;
foreach (string windowHandle in driver.WindowHandles)
if (windowHandle != currentWindow)
driver.SwitchTo().Window(windowHandle);//Perfprm Actions on new Window
driver.Close(); //Close the new Window
break;
driver.SwitchTo().Window(currentWindow);//switch back to the original window
How to Handle Frames
Switching to Frame by index
Driver.SwitchTo().Frame(0); //Switch to First Frame
Switching to Frame by Name and Id
Driver.SwitchTo().Frame(“frameName”); //Switch to Frame by Name or ID
Switching back to Default content
Driver.SwitchTo().DefaultContent; //Switch to the Main Content
Methods Under Switch Commands
ActiveElement - Switches focus to element that has focus at the moment. If there’s no
element with focus, this method will switch to body element of the page.
Alert - Switches focus to currently active dialog box
DefaultContent - Switches focus to the first frame on the page or main document if
page contains iframes.
Frame - Switches focus to frame by given index
ParentFrame - Switches focus to parent frame of currently selected frame
Window - Switches focus to the window with specified name
Waits
Implicit Wait
Selenium has a built-in way to automatically wait for elements called an implicit wait. An implicit wait
value can be set either with the timeouts capability in the browser options, or with a driver method.
This is a global setting that applies to every element location call for the entire session. The default
value is 0, which means that if the element is not found, it will immediately return an error. If an
implicit wait is set, the driver will wait for the duration of the provided value before returning the
error. Note that as soon as the element is located, the driver will return the element reference and
the code will continue executing, so a larger implicit wait value won’t necessarily increase the
duration of the session.
Note: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For
example, setting an implicit wait of 10 seconds and an explicit wait of 15 seconds could cause a
timeout to occur after 20 seconds.
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
Explicit Wait
Explicit waits are loops added to the code that poll the application for a specific condition to evaluate
as true before it exits the loop and continues to the next command in the code. If the condition is not
met before a designated timeout value, the code will give a timeout error. Since there are many ways
for the application not to be in the desired state, so explicit waits are a great choice to specify the
exact condition to wait for in each place it is needed. Another nice feature is that, by default, the
Selenium Wait class automatically waits for the designated element to exist.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2));
wait.Until(d => btn.Displayed)
Fluent Wait:
The Wait class can be instantiated with various parameters that will change how the conditions are
evaluated.
This can include:
Changing how often the code is evaluated (polling interval)
Specifying which exceptions should be handled automatically
Changing the total timeout length
Customizing the timeout message
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2))
PollingInterval = TimeSpan.FromMilliseconds(300),
};
wait.IgnoreExceptionTypes(typeof(ElementNotInteractableException));
wait.Until(d => {
revealed.SendKeys("Displayed");
return true;
});
File Handling
File Upload
Because Selenium cannot interact with the file upload dialog, it provides a way to upload files
without opening the dialog. If the element is an input element with type file, you can use the send
keys method to send the full path to the file that will be uploaded.
IWebElement fileInput = driver.FindElement(By.CssSelector("input[type=file]"));
fileInput.SendKeys(uploadFile);
driver.FindElement(By.Id("file-submit")).Click
Drag and Drop
To perform the drag-drop action through a Selenium script, there is no direct drag-drop method
available in WebElement interface. Unlike other commands like click(), sendKeys() there is nothing
available for drag and drop. Here, we leverage the Actions class which provides various methods of
emulating such complex interactions.
So, here are the methods Actions class provides for Drag-Drop action:
dragAndDrop(WebElementsource, WebElement target)
dragAndDropBy(WebElementsource, int xOffset, int yOffset)
// Drag and drop (using Actions class)
protected void DragAndDrop(By source, By target)
var actions = new Actions(Driver);
actions.DragAndDrop(FindElement(source), FindElement(target)).Build().Perform();
Sorting
List<String> displayNames = new List<string>();
// grab the cells that contain the display names you want to verify are sorted
IReadOnlyList<IWebElement> cells = Driver.FindElements(locator);
// loop through the cells and assign the display names into the ArrayList
foreach (IWebElement cell in cells)
displayNames.Add(cell.Text);
// make a copy of the displayNames array
List<String> displayNamesSorted = new List<string>(displayNames);
displayNamesSorted.Sort();
Console.WriteLine(displayNames.SequenceEqual(displayNamesSorted));
OR
var cells = WebDriver.FindElements(locator);
Assert.IsTrue(cells.OrderBy(c => c.Text).SequenceEqual(cells));
How To Handle Dropdown
Selenium.Support: it’s the package that enables us to work with dropdowns in Selenium.
The SelectElement Class
The SelectElement class in Selenium C# is part of the Selenium.Support NuGet package. It allows us
to interact with the dropdown and multiple select menus on web pages.
It also allows you to select and deselect options from the dropdown, validate if it allows multiple
selections, see all the available options, and see what options are currently selected.
Methods in the SelectElement class:
SelectByValue(): will select the option based on the value from the HTML.
SelectByText(): used to select the dropdown option based on the displayed text.
SelectByIndex(): selects the option based on index. The index starts from 0, not 1!
SelectedOption(): returns the selected WebElement.
AllSelectedOptions(): returns a list of the selected WebElements. It should be used only on
multiple selections.
IsMultiple(): a boolean attribute with the value True if the selection allows multiple
selections and False if it doesn’t.
DeelectByValue(): will deselect the option based on its value.
DeselectByText(): used to deselect the dropdown option based on the text.
DeselectByIndex(): deselects the option based on index.
DeselectAll(): will deselect all previously selected options.
//Generic method for Select.
protected void SelectDropDownOpton(By by, string option, SelectBy selectBy = SelectBy.Text)
var dropdown = new SelectElement(FindElement(by));
switch (selectBy)
case SelectBy.Text:
dropdown.SelectByText(option);
break;
case SelectBy.Value:
dropdown.SelectByValue(option);
break;
case SelectBy.Id;
dropdown.SelectByValue(option); // Using Value as ID SelectElement doesnt provide SelectedByID Directly
break;
default:
throw new ArgumentOutOfRangeException(nameof(selectBy), selectBy, "Invalid SelectBy Option");
Sample Selenium Code
// Generic Base Page Class
using OpenQA.Selenium;
namespace SeleniumFramework
{
public class BasePage
{
protected IWebDriver Driver;
protected WebDriverWait Wait;
public BasePage(IWebDriver driver)
{
Driver = driver;
Wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
}
protected IWebElement FindElement(By by)
{
return Driver.FindElement(by);
}
// Generic method for finding a list of elements
protected List<IWebElement> FindElements(By by)
{
Wait.Until(ExpectedConditions.ElementIsVisible(by));
return new List<IWebElement>(Driver.FindElements(by));
}
protected void ClickElement(By by)
{
FindElement(by).Click();
}
protected void TypeText(By by, string text)
{
FindElement(by).SendKeys(text);
}
protected string GetText(By by)
{
return FindElement(by).Text;
}
protected void UploadFile(By by, string filePath)
{
FindElement(by).SendKeys(filePath);
}
//Drag and drop (using Actions class)
protected void DragAndDrop(By source, By target)
{
var actions = new Actions(Driver);
actions.DragAndDrop(FindElement(source),
FindElement(target)).Build().Perform();
}
// Switch to frame
protected void SwitchToFrame(By frameLocator)
{
Driver.SwitchTo().Frame(FindElement(frameLocator));
}
// Window handler (switch to a new window)
protected void SwitchToNewWindow()
{
var mainWindow = Driver.CurrentWindowHandle;
var allWindows = Driver.WindowHandles;
foreach (var window in allWindows)
{
if (window != mainWindow)
{
Driver.SwitchTo().Window(window);
break;
}
}
}
// Alert handling
protected void AcceptAlert()
{
Driver.SwitchTo().Alert().Accept();
}
protected void DismissAlert()
{
Driver.SwitchTo().Alert().Dismiss();
}
// Enhanced SelectDropdownOption method
protected void SelectDropdownOption(By by, string option, SelectBy
selectBy = SelectBy.Text)
{
var dropdown = new SelectElement(FindElement(by));
switch (selectBy)
{
case SelectBy.Text:
dropdown.SelectByText(option);
break;
case SelectBy.Value:
dropdown.SelectByValue(option);
break;
case SelectBy.Id:
dropdown.SelectByValue(option); // Note: Using value as
ID since SelectElement doesn't provide SelectById directly
break;
default:
throw new ArgumentOutOfRangeException(nameof(selectBy),
selectBy, "Invalid SelectBy option");
}
}
// Enumeration for select options
public enum SelectBy
{
Text,
Value,
Id
}
}
}
Now, let's create a sample page using the base class:
using OpenQA.Selenium;
namespace SeleniumFramework
{
public class HomePage : BasePage
{
// Define locators using By
private By searchInput = By.CssSelector("input[type='text']");
private By searchButton = By.CssSelector("button[type='submit']");
private By resultMessage = By.CssSelector("#result-message");
public HomePage(IWebDriver driver) : base(driver)
{
}
// Define methods for actions on the page
public void Search(string query)
{
TypeText(searchInput, query);
ClickElement(searchButton);
}
public string GetResultMessage()
{
return GetText(resultMessage);
}
}
}
Now, in your test class:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
namespace SeleniumFramework
{
[TestFixture]
public class TestSuite
{
IWebDriver driver;
HomePage homePage;
[SetUp]
public void Setup()
{
driver = new ChromeDriver();
homePage = new HomePage(driver);
homePage.ImplicitWait(10); // Set implicit wait
[Test]
public void SampleTest()
{
driver.Navigate().GoToUrl("https://www.example.com");
homePage.Search("Selenium Framework");
Assert.AreEqual("Search results for: Selenium Framework",
homePage.GetResultMessage());
}
[TearDown]
public void Teardown()
{
driver.Quit();
}
}
}