Selenium automates browsers. That's it!
What you do with that power is entirely up to you.
Primarily it is for automating web applications for testing purposes, but is certainly not limited to just that.
Boring web-based administration tasks can (and should) also be automated as well.
Selenium WebDriver Commands
Browser Commands
- get(String arg0): void – This method Load a new web page in the current browser window.
- getTitle(): String – This method fetches the Title of the current page.
- getCurrentUrl(): String – This method fetches the string representing the Current URL which is opened in the browser.
- getPageSource(): String – This method returns the Source Code of the page.
- close(): void – This method Close only the current window the WebDriver is currently controlling.
- quit(): void – This method Closes all windows opened by the WebDriver.
Selenium Navigation Commands
- navigate().to(String arg0): void – This method Loads a new web page in the current browser window.
- navigate().forward() : void – This method does the same operation as clicking on the Forward Button of any browser.
- navigate().back() : void – This method does the same operation as clicking on the Back Button of any browser.
- navigate().refresh() : void – This method Refresh the current page. It neither accepts nor returns anything.
Selenium WebElement Commands
- clear( ) : void – If this element is a text entry element, this will clear the value.
- sendKeys(CharSequence… keysToSend ) : void – This simulates typing into an element, which may set its value.
- click( ) : void – This simulates the clicking of any element. Accepts nothing as a parameter and returns nothing.
- isDisplayed( ) : boolean – This method determines if an element is currently being displayed or not.
- isEnabled( ) : boolean – This determines if the element currently is Enabled or not?
- isSelected( ) : boolean – Determine whether or not this element is selected or not?
- submit( ) : void– This method works well/better than the click() if the current element is a form, or an element within a form.
- getText( ) : String – This method will fetch the visible (i.e. not hidden by CSS) innerText of the element.
- getTagName( ) : String – This method gets the tag name of this element.
- getCssvalue( ) : String – This method Fetch CSS property value of the give element.
- getAttribute(String Name) : String – This method gets the value of the given attribute of the element.
- getSize( ) : Dimension – This method fetch the width and height of the rendered element.
- getLocation( ) : Point – This method locate the location of the element on the page.
How to Find Element in Selenium?
Finding elements in Selenium WebDriver is done by using the findElement(By.locator()) method
- id(String id): By – This is the most efficient and preferred way to find an element in Selenium, as most of the time IDs are unique.
- name(String name): By– This is also an efficient way to locate an element but again the problem is same as with ID that UI developer makes it having non-unique names on a page or auto-generating the names.
- className(String className): By – This finds elements based on the value of the CLASS attribute.
- tagName(String name): By – With this, you can find elements by their TAGNAMES.
- linkText(String linkText) : By – With this you can find elements of "a" tags(Link) with the link names.
- partialLinkText(String linkText) : By – With this you can find elements of "a" tags(Link) with the partial link names.
- xpath(String xpathexpression) : By – It is the most popular and majorly used locating element technique or the easiest way to locate an element in WebDriver.
- cssSelector(String cssexpression) : By - Locates elements matching a CSS selector.
CheckBox & Radio Button Operations
- By ID
- With IsSelected
- With Value
- By CssSelector
DropDown & Multiple Select Operations
You can choose it by ID, Name, CSS & Xpath, etc.
- org.openqa.selenium.support.ui.Select package and to use it we need to create a new Select Object of class Select.
- Select oSelect = new Select());
- selectByVisibleText(String arg0) : void – It is very easy to choose or select an option given under any dropdowns and multiple selection boxes with selectByVisibleText method.
- selectByIndex(int arg0) : void – It is almost the same as selectByVisibleText but the only difference here is that we provide the index number of the option here rather the option text.
- selectByValue(String arg0) : void – It is again the same as what we have discussed earlier, the only difference in this is that it asks for the value of the option rather than the option text or index.
- getOptions( ) : List(WebElement) – This gets the all options belonging to the Select tag.
- deselectAll( ) : void – Clear all selected entries. This is only valid when the SELECT supports multiple selections.
- deselectByIndex(int arg0) : void – Deselect the option at the given index.
- deselectByValue(String arg0) : void – Deselect all options that have a value matching the argument.
- deselectByVisibleText(String arg0) : void – Deselect all options that display text matching the argument.
- isMultiple( ) : boolean – This tells whether the SELECT element support multiple selecting options at the same time or not.
Handling Web Tables, Frames, And Dynamic Elements
This tutorial consists of 3 different topics and their handling mechanisms in selenium script.
- Web Tables/HTML tables
- Frames
- Dynamic elements
Approach #1:
Below is the xpath of one of the cell in html table.
//div[@id:'main']/table[1]/tbody/tr[1]/th[1]
//*[@id:'main']/table[1]/tbodyApproach #2:
The first approach is best suitable for the table which doesn't change its dimensions and always remains the same. Above approach will not be a perfect solution for dynamically changing web tables.
//*[contains(@id,'username')]
//*[contains(text(),'LogIn')]
//*[contains (@placeholder, 'Organization')]
//input[contains (@name, 'organization')]
//*[contains(@class, 'sign-up-input')]Approach #3:
In this section we will learn different ways to handle dynamic element and construct generic Xpath. In few scenarios, element attributes change dynamically. It can be 'id', 'name' etc.
//input [@name:’password’]
//*[@id:’email_01’]
//input[name:’email’][@placeholder:’Work Email’]List of XPath Locators
Basic XPath
//input [@name:’password’]
//a [@href: ‘https://www.lambdatest.com/’]
//*[@id:’email_01’]
//input[name:’email’][@placeholder:’Work Email’]XPath for Tables
//div[@id:'main']/table[1]/tbody/tr[1]/th[1]
//*[@id:'main']/table[1]/tbodyXPath using Text
//button[text():'Signup for Free']
//button[contains(text(),'Signup')]XPath using Index
//div[@class: 'col-sm-12 google-sign-form']/input[2]XPath using AND/OR operator
//input[@placeholder :'Full Name' and @type : 'text']
//input[@type: 'email' and @name: 'email']
//input[@placeholder :'Full Name' or @type : 'text']
//input[@type: 'email' or @name: 'email']XPath using Contains Keyword
//*[contains(@id,'username')]
//*[contains(text(),'LogIn')]
//*[contains (@placeholder, 'Organization')]
//input[contains (@name, 'organization')]
//*[contains(@class, 'sign-up-input')]XPath using Start-with Keyword
//*[starts-with(@id,'user')]
/input[starts-with(@placeholder, 'Organization)]
//input[starts-with(@name, 'organization)]XPath using Parent-Child
//*[@id:'rt-feature']//parent::divXPath using Following Siblings
//div[@class:'canvas- graph']//a[@href:'/accounting.html'][i[@class:'icon-usd']]/following-sibling::h4XPath using ANCESTOR
//tag[@attribute :'Attribute_Value']//ancestor::parent_node
//label[text():'Full Name']/ancestor::form
//tag[@attribute :'Attribute_Value']//child::child_node
//form[@id:'userForm']/child::div[1]//label
//node[attribute:'value of attribute']//descendant::attribute
//div[@class: 'custom-control custom-radio custom-control-inline']/descendant::input
//a[contains(text(),'Inside div block 2.')]/ancestor::div//aXPath using Parent Axis
//tag[@attribute :'Attribute_Value']//ancestor::parent_node
//input[@id:'yesRadio']/parent::divXPath using Following Axis
//node[attribute:'value of attribute']//following::attribute
//input[@id:'userName']/following::textareaXPath using Following sibling Axis
//node[attribute:'value of attribute']//following-sibling::attribute
//div[@class:'col-md-3 col-sm-12']/following-sibling::divXPath using Preceding Axis
//node[attribute:'value of attribute']//preceding::attribute
//input[@id:'userName']/preceding::labelClass Actions
Common Actions Methods:
- build() : Action - Generates a composite action containing all actions so far, ready to be performed
- click() : Action – Clicks at the current mouse location
- click(WebElement target) : Action – Clicks in the middle of the given element
- clickAndHold() : Action – Clicks (without releasing) at the current mouse location
- clickAndHold(WebElement target) : Action – Clicks (without releasing) in the middle of the given element
- contextClick() : Action – Performs a context-click at the current mouse location
- contextClick(WebElement target) : Action – Performs a context-click at middle of the given element
- doubleClick() : Action – Performs a double-click at the current mouse location
- doubleClick(WebElement target) : Action – Performs a double-click at middle of the given element
- dragAndDrop(WebElement source, WebElement target) : Action – A convenience method that performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse
- dragAndDropBy(WebElement source, int xOffset, int yOffset) : Action – A convenience method that performs click-and-hold at the location of the source element, moves by a given offset, then releases the mouse
- keyDown(java.lang.CharSequence key) : Action – Performs a modifier key press
- keyDown(WebElement target, java.lang.CharSequence key) : Action – Performs a modifier key press after focusing on an element
- keyUp(java.lang.CharSequence key) : Action – Performs a modifier key release
- keyUp(WebElement target, java.lang.CharSequence key) : Action – Performs a modifier key release after focusing on an element
- moveByOffset(int xOffset, int yOffset) : Action – Moves the mouse from its current position (or 0,0) by the given offset
- moveToElement(WebElement target) : Action – Moves the mouse to the middle of the element
- moveToElement(WebElement target, int xOffset, int yOffset) : Action – Moves the mouse to an offset from the top-left corner of the element
- pause(java.time.Duration duration) : Action
- pause(long pause) : Action – Performs a pause
- perform() : Action – A convenience method for performing the actions without calling build() first
- release() : Action – Releases the depressed left mouse button at the current mouse location
- release(WebElement target) : Action – Releases the depressed left mouse button, in the middle of the given element
- sendKeys(java.lang.CharSequence... keys) : Action – Sends keys to the active element
- sendKeys(WebElement target, java.lang.CharSequence... keys) : Action – Equivalent to calling: Actions.click(element).sendKeys(keysToSend)
- tick(Action action) : Action
- tick(Interaction... actions) : Action
List of CSS Selectors
Basic CSS
#id
#username
tagname#id
input#id
.class
tag.classWait Commands in Selenium
There are 3 types of Synchronization or Wait statement in selenium WebDriver:
Implicit Wait
Sets internally a timeout that will be used for all consecutive Web Element searches. It will try look up the element repeatedly for the specified amount of time before throwing a NoSuchElementException if the element could not have been found.
Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. Once this time is set, WebDriver will wait for the element before the exception occurs.
driver.manage().timeouts().implicitlywait(20L,Timeunit.sec);Explicit Wait
Just Wait is a one-timer used for a particular search. I can set it up wait, for any condition I might like. Usually, I can use some of the prebuilt Expected Conditions to wait for elements to become clickable, visible, invisible, etc.
By using Explicit Wait command, the WebDriver is directed to wait until a certain condition occurs before proceeding with executing the code.
- alertIsPresent()
- elementToBeClickable()
- presenceOfElementLocated()
- visibilityOfElementLocated()
- textToBePresentInElement()
- titleIs()
- And more...
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));Fluent Wait
Let's say I have an element which sometimes appears in just 1 second and some time it takes minutes to appear. In that case, I have been using fluent wait, as this will try to find element again and again until it finds it or until the final timer runs out.
The Fluent Wait command defines the maximum amount of time for Selenium WebDriver to wait for a certain condition to appear. It also defines the frequency with which WebDriver will check if the condition appears.
Wait wait = new FluentWait (WebDriver)(driver)
.withTimeout(50, TimeUnit.SECONDS)
.pollingevery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);Exception Handling in Selenium
What is an Exception?
"Exception" is a standard term used by software programmers regardless of any programming language that is used to write the code. "Exception" as the name suggests is an unusual event or an uncommon case that disrupts the normal flow of program execution.
The Exceptions are classified mainly into two types:
- Checked Exceptions: These exceptions are handled while writing the code itself before the compilation of the code, and hence they are examined at the compile time.
- Unchecked Exceptions: These exceptions get thrown at run time and are more catastrophic as compared to Checked Exception.
10 Common Exceptions in Selenium WebDriver
- ElementNotVisibleException: In spite of the element being present in the DOM, it is not visible (can not be interactive).
- ElementNotSelectableException: An element is disabled (can not be clicked/selected) in spite of being present in the DOM
- NoSuchElementException: Webdriver is not able to determine the elements during runtime
- NoSuchFrameException: Webdriver attempts to switch to an invalid frame, which is unavailable
- NoAlertPresentException: Webdriver is trying to switch to an invalid alert, which is unavailable
- NoSuchWindowException: Webdriver is trying to switch to an invalid window, which is unavailable
- StaleElementReferenceException: The referenced element is no longer present on the DOM page
- SessionNotFoundException: Webdriver is acting immediately after 'quitting' the browser
- TimeoutException: The command did not complete in the specified time
- WebDriverException: Webdriver is acting immediately after 'closing' the browser
Handling Exceptions In Selenium WebDriver
Following are a few standard ways using which one can handle Exceptions in Selenium WebDriver:
Try-catch:
This method can catch Exceptions by using a combination of the try and catch keywords.
try {
//Some code -
}
catch(Exception e) {
//Code for Handling the exception -
}Multiple catch blocks:
There are various types of Exceptions, and one can expect more than one exception from a single block of code.
try {
//Some code -
}
catch(ExceptionType1 e1) {
//Code for Handling the Exception 1 -
}
catch(ExceptionType2 e2) {
//Code for Handling the Exception 2 -
}Throw/Throws:
When a programmer wants to generate an Exception explicitly, the Throw keyword is used.
public static void anyFunction() throws Exception {
//try { write your code here
}
catch(Exception e) {
//Do whatever you wish to do here
//Now throw the exception back to the system
//throw(e);
}
}Finally:
The Final keyword is used to create a block of code under the try block. This final code block always executes irrespective of the occurrence of an exception.
try {
//Protected code -
}
catch(ExceptionType1 e1) {
//Catch block -
}
finally {
//The finally block always executes. -
}Methods to display Exception Information:
- printStackTrace(): It prints the stack trace, name of the exception, and other useful description
- toString(): It returns a text message describing the exception name and description
- getMessage(): It displays the description of the exception
Frequently Asked Questions
How do you launch IE | Chrome | Firefox (gecko driver) browser?
String basPath = System.getProperty("user.dir");
String chromePath = basPath + "\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromePath);
WebDriver driver = new ChromeDriver();Difference between implicitly Wait, Explicit wait & Fluent Wait
Implicit Wait - sets internally a timeout that will be used for all consecutive Web Element searches.
Explicit Wait - or just Wait is a one-timer used for a particular search. I can set it up wait, for any condition I might like.
Fluent Wait - Let's say I have an element which sometimes appears in just 1 second and some time it takes minutes to appear.
What is the difference between find element and find elements?
find element() – is used to find the one web element. It returns only one WebElement type.
find elements() - is used to find more than one web element. It returns List of WebElements.
Difference between single and double slash in X-path?
Absolute Path: Single slash '/' - Start selection from the document node, Used to identify the immediate child
Relative Path: Double Slash '//' - Start selection matching anywhere in the document & search in the entire structure. By writing Relative path can capture the Dynamic Element of the object.
How to find total number of iFrames on a web page | Switch to Frames
Switch between Window
Private void handlingMultipleWindows(String windowTitle) {
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
driver.switchTo().window(window);
if (driver.getTitle().contains(windowTitle)) { return; }
}
}
Switch by frame name
driver.switchTo().frame("iframe1");
Switch by frame ID
driver.switchTo().frame("IF1");
Switch back to the main window
driver.switchTo().defaultContent();How do you simulate scroll down action?
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript("window.scrollBy(0,4500)", "");
Thread.sleep(3000);
jsx.executeScript("window.scrollBy(450,0)", "");Selenium Grid
What is Selenium Grid?
Selenium-Grid allows you to run your tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines, different browsers, and operating systems. Essentially, Selenium-Grid support distributed test execution. It allows for running your tests in a distributed test execution environment.
Configuration of Selenium Grid
Starting a hub
java -jar selenium-server-standalone-3.1.2.jar -role hub
Registering a node to the hub
java -jar selenium-server-standalone-3.1.2.jar -role webdriver hub
http://localhost:4444/grid/register -port 5555
Setting up supported browser names
java -jar selenium-server-standalone-3.1.2.jar -role webdriver hub
http://localhost:4444/grid/register -port 5555 -browser browserName=firefox -browser
browserName=iexplore -browser browserName=chrome
Setting up max instances
java -jar selenium-server-standalone-3.1.2.jar -role webdriver r hub
http://localhost:4444/grid/register -port 5555
-browser browserName=firefox, maxInstances=2
-browser browserName=iexplore, maxInstances=2
-browser browserName=chrome, maxInstances=2 -maxSession 6
Setting up chrome|Firfox|IE driver
-Dwebdriver.chrome.driver=Cl\Softwares\chromedriver.exe
-Dwebdriver.gecko.driver=Cl\Softwares\geckoDriverServer.exe
-Dwebdriver.ie.driver=Cl\Softwares\IEDriverServer.exe
Final Command
Java
-Dwebdriver.chrome.driver= C:\Softwares\chromedriver.exe
-Dwebdriver.gecko.driver=Cl\Softwares\geckoDriverServer.exe
-Dwebdriver.ie.driver= C:\Softwares\IEDriverServer.exe
-jar selenium-server-standalone-2.32.0.jar -role webdriver
-hub http://localhost:4444/grid/register -port 5555 -browser
browserName=firefox,maxInstances=2 -browser browserName=iexplore -browser
browserName=chrome,maxInstances=3 -maxSession 5JAVA & TestNG
TestNG annotations vs JUnit annotations
TestNG: @Test,@Parameters,@Listeners,@BeforeSuite,@AfterSuite,@BeforeTest,@AfterTest, @DataProvider,@BeforeGroups,@AfterGroups,@BeforeClass,@AfterClass, @BeforeMethod, @AfterMethod, @Factory
JUnit: @Test @Before @After @AfterClass @BeforeClass @Ignore @Runwith
6 assertions of TestNG
- assertEquals
- assertNotEquals
- assertTrue
- assertFalse
- assertNull
- assertNotNull
In TestNG how can you disable a test?
To disable the test case, you can use the following annotation:
- @Test(enabled = false)
- Exclude key word in testNG.xml file inside the method
How do you read data from excel?
File f = new File("c://excel.xlsx");
FileInputStream fis = new FileInputStream (f);
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet("sheetName");
Row r = s.getRow(0);
Cell c = r.getCell(0);
SeleniumHQ on GitHub