Exceptions are faults or disruptions that occur during the execution of a program/application. Exception handling is crucial for maintaining the natural or normal flow of the application. Selenium exceptions can be broadly categorized into two types: Checked and Unchecked
Exceptions.
Checked exceptions are handled during the coding process itself. Unchecked exceptions occur during run-time and can have a much greater impact on the application flow. We have compiled some of the most common selenium exceptions along with the various ways to
handle them.
Most Common Selenium Exceptions
- NoSuchWindowException
- NoSuchFrameException
- NoSuchElementException
- NoAlertPresentException
- InvalidSelectorException
- TimeoutException
- ElementNotVisibleException
- ElementNotSelectableException
- NoSuchSessionException
- StaleElementReferenceException
Selenium is an open source umbrella project for a range of tools and libraries aimed at supporting browser automation. It provides a playback tool for authoring functional tests across most modern web browsers, without the need to learn a test scripting language.
Most programmers and developers who build website applications and wish to test them every now and then use Selenium. One of the biggest advantages of Selenium, which has made it so popular, is its flexibility. Any individual who creates web programs can use Selenium to test the code and applications. Further, professionals can debug and perform visual regression tests as per the requirements of the website or code.
Automation testing is a Software testing method or technique to test any application and compare the actual result with the expected result. This can be achieved by designing test scripts using any relevant automation testing tool. Now a days Automation is vastly used to automate repetitive tasks and other testing tasks which are difficult to perform manually.
In manual testing test cases are executed manually without any proper support from relevant tools. However, for automated testing, test cases are executed with the assistance of one or more appropriate tools. Automation Testing is also more reliable as there is less chances of human error. In manual testing we have to run test cases manually every time based on our need, hence it is time consuming. However, in
automation testing once scripts are ready we can run the test cases any number of time with different combination of data with minimal time.
Selenium IDE, a Firefox add-on that you can only use in creating relatively simple test cases and test suites.
Selenium Remote Control, also known as Selenium 1, which is the first Selenium tool that allowed users to use programming languages in creating complex tests.
WebDriver, the newer breakthrough that allows your test scripts to communicate directly to the browser, thereby controlling it from the OS level.
Selenium Grid is also a tool that is used with Selenium RC to execute parallel tests across different browsers and operating systems.
- Selenium is open source and free software and hence there is no licensing cost for its usage.
- Scripting can be done in most of the widely used programming languages like Java, C#, Ruby, Perl, PHP and Python
- Automation using selenium can be done in many OS platform like MS Windows, Macintosh and Linux
- It supports most of the popular browsers like Chrome, FireFox, Internet Explorer, Opera and Safari.
- Selenium Grid helps in parallel and distributed testing
- It uses less Hardware resources
- Selenium does not provide desktop application automation support.
- Web Services – REST or SOAP cannot be automated using selenium.
- Selenium WebDriver requires programming language requirement for script creation.
- No vendor support for tool compared to commercial tools like HP UFT
- As there is no object repository concept in Selenium, maintainability of objects becomes difficult
- For performing common tasks required in automation like logging, reading-writing to external files we have to rely on external libraries
- Faster than other tools of Selenium suite (IDE, RC)
- Control the browser by programming
- Supports Data driven Testing and Cross browser testing
- Supports Parallel test execution with the help of either JUnit or TestNG
The locator can be termed as an address that identifies a web element uniquely within the webpage. Locators are the HTML properties of a web element.
- ID – driver.findElement(By.id(“IdName”))
- Name – driver.findElement(By.name(“Name”))
- Class Name – driver.findElement(By.className(“Element Class”))
- Tag Name – driver.findElement(By.tagName(“HTML Tag Name”))
- Link Text – driver.findElement(By.linkText(“LinkText”))
- Partial Link Text – driver.findElement(By.partialLinkText(“partialLinkText”))
- CSS Selector – driver.findElement(By.cssSelector(“value”))
- XPath – driver.findElement(By.xpath(“XPath”))
driver – Object/Instance of WebDriver
findElement – WebDriver method
By – Pre-defined Class in Selenium
id – Element locater/attribute
IdName – Locator value
Basic Xpath – XPath expression select nodes or list of nodes on the basis of attributes like ID , Name, Classname, etc. from the XML document.
Contains() – Contains() is a method used in XPath expression. It is used when the value of any attribute changes dynamically.
Using OR & AND – In OR expression, two conditions are used, whether 1st condition OR 2nd condition should be true. It is also applicable if any one condition is true or maybe both. Means any one condition should be true to find the element.
Starts-with() – It is used to identify an element, when we are familiar with the attributes value (starting with the specified text) of an element
Text() – This mechanism is used to locate an element based on the text available on a webpage.
Following – By using this we could select everything on the web page after the closing tag of the current node.
Ancestor – The ancestor axis selects all ancestors element (grandparent, parent, etc.) of the current node.
Child – Selects all children elements of the current node.
Preceding – Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes.
Following-sibling – Select the following siblings of the context node. Siblings are at the same level of the current node.
Parent – Selects the parent of the current node.
position() – Selects the element out of all input element present depending on the position number provided
Xpath Symbols
//tagname[@attribute-name=’value1′]
//*[@attribute-name=’value1′]
Xpath Generation using different other methods
Xpath=//*[contains(@type,'sub')]
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Xpath=//label[starts-with(@id,'message')]
Xpath=//td[text()=‘textname']
Xpath=//*[@type='text']//following::input
Xpath=//*[text()=‘textvalue']//ancestor::div
Xpath=//*[@id=‘idname']/child::li
Xpath=//*[@type=‘typename']//preceding::input
Xpath=//*[@type=' typename ']//following-sibling::input
Xpath=//*[@id=' idname']//parent::div
Absolute Xpath: It uses Complete path from the Root Element to the desire element.
Example: /HTML/body/div/div[@id=’Email’]
Relative Xpath: You can simply start by referencing the element you want and go from there. Always Relative Xpaths are preferred as they are not the complete paths from the Root element. … So Always use Relative Xpaths in your Automation.
Example: //span[@class=’Email’]
/ -> Selects from the root node
// ->Selects nodes in the document from the current node that match the selection no matter where they are
CSS can be generated using different methods:
css=
css=
css=;
Example: input[type=submit]
css=tag.class[attribute=value]
Starts with (^): css=
End with (^): css=
Contains (*): css=
Example: css=input[id*='id']
Using Multiple Symbols:
css = tagname[attribute1='value1'][attribute2='value2']
You can use “submit” method on element to submit a form after all mandatory information filled.
Example: element.submit();
find element(): It finds the first element within the current page using the given “locating mechanism”. It returns a single WebElement. It is the responsibility of developers and testers to make sure that web elements are uniquely identifiable using certain properties such as ID or name.
Syntax: WebElement userid = driver.findElement(By.id(“Id Value”));
findElements() : Using the given “locating mechanism” it will find all the elements within the current page. It returns a list of web elements. It returns an empty list if there are no elements found using the given locator strategy and locator value.
Syntax: List elementName = driver.findElements(By.LocatorStrategy(“LocatorValue”));
TypeKeys() will trigger JavaScript event in most of the cases whereas .type() won’t. Type key populates the value attribute using JavaScript whereas .typekeys() emulates like actual user typing
Assert: Assert allows to check whether an element is on the page or not. The test will stop on the step failed, if the asserted element is not available. In other words, the test will terminated at the point where check fails.
Verify: Verify command will check whether the element is on the page, if it is not then the test will carry on executing. In verification, all the commands are going to run guaranteed even if any of test
To click on specific part of element, you would need to use clickAT command. ClickAt command accepts element locator and x, y co-ordinates as arguments- clickAt (locator, cordString)
driver.findElement(By.xpath(“xpath”)).sendKeys(Keys.ENTER);
The Implicit Wait in Selenium is used to tell the web driver to wait for a certain amount of time before it throws a “No Such Element Exception”. The default setting is 0. Once we set the time, the web driver will wait for the element for that time before throwing an exception.
Selenium Web Driver has borrowed the idea of implicit waits from Watir.
Before Selenium 4 –
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Now we will see this as deprecated @Deprecated WebDriver.Timeouts implicitlyWait(long time, TimeUnit unit);
After Selenium 4 –
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
The Explicit Wait in Selenium is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or maximum time exceeded before throwing “ElementNotVisibleException” exception. It is an intelligent kind of wait, but it can be applied only for specified elements. It gives better options than implicit wait as it waits for dynamically loaded Ajax elements.
Once we declare explicit wait we have to use “ExpectedConditions” or we can configure how frequently we want to check the condition using Fluent Wait. These days while implementing we are using Thread.Sleep() generally it is not recommended to use.
Before Selenium 4 –
//Old syntax
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(“.classlocator”)));
After Selenium 4 –
//Selenium 4 syntax
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(“.classlocator”)));
The Fluent Wait in Selenium is used to define maximum time for the web driver to wait for a condition, as well as the frequency with which we want to check the condition before throwing an “ElementNotVisibleException” exception. It checks for the web element at regular intervals until the object is found or timeout happens.
Frequency: Setting up a repeat cycle with the time frame to verify/check the condition at the regular interval of time.
FluentWait wait = new FluentWait(driver);
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement) {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("element"));
}
});
findElement () will return only single WebElement and if that element is not located or we use some wrong selector then it will throw NoSuchElement exception.
findElements() – FindElements in Selenium command takes in By object as the parameter and returns a list of web elements. It returns an empty list if there are no elements found using the given locator strategy and locator value.
WebElement demos=driver.findElement(By.xpath(""//*[@id='menu-top']/li[1]/a""));
List links=driver.findElements(By.xpath("".//*[@id='menu-top']/li""));
- Datadriven framework: In this framework, the test data is separated and kept outside the Test Scripts, while test case logic resides in Test Scripts. Test data is read from the external files ( Excel Files) and are loaded into the variables inside the Test Script. Variables are used for both for input values and for verification values.
- Keyworddriven framework: The keyword driven frameworks requires the development of data tables and keywords, independent of the test automation. In a keyword driven test, the functionality of the application under test is documented in a table as well as step by step instructions for each test.
To work with Basic Authentication pop-up (which is a browser dialogue window), you just need to send the user name and password along with the application URL.
#1 (Chrome & Firefox)
By passing user credentials in URL. Its simple, append your username and password with the URL.
e.g., http://Username:Password@SiteURL
http://rajkumar:myPassword@www.hireqa.co.in
#2 (IE)
First create AutoIt script as below and save it as basicauth.au3
To pass user name and password
WinWaitActive(""Windows Security"")
Send(""admin"")
Send(""{TAB}"")
Send(""admin"")
Send(""{ENTER}"")
--------------------------------------------------
try {
Runtime.getRuntime().exec(""E:/basicauth.exe"");
} catch (Exception e) {
e.printStackTrace();
}
WebDriverManager class in Selenium:
- automates the management of WebDriver binaries.
- downloads the appropriate driver binaries, if not already present, into the local cache.
- downloads the latest version of the browser binary, unless otherwise specified.
- Eliminates the need to store driver binaries locally. We also need not maintain various versions of the binary driver files for different browsers.
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
ChromeOptions chromeOptions = new ChromeOptions();
WebDriverManager.chromedriver().driverVersion(“85.0.4183.38”).setup();
WebDriverManager.chromedriver().browserVersion(“83.0.4103”).setup();
WebDriver driver = new ChromeDriver(chromeOptions);
"WebDriverManager.chromedriver().architecture(io.github.bonigarcia.wdm.Architecture.X32).setup();
Alternatively, we can also use arch32() or arch64() methods to specify binary types.
chromedriver().arch32().setup();
chromedriver().arch64().setup();"
If your organization has a proxy server, you need to specify proxy server details like server name or IP address, username, and password to the WebDriverManager. Otherwise, it may raise/ cause errors like io.github.bonigarcia.wdm.WebDriverManagerException: java.net.UnknownHostException: chromedriver.storage.googleapis.com.
WebDriverManager.chromedriver()
.version(“83.0.0”)
.arch32()
.proxy(“proxyhostname:80”)
.proxyUser(“username”)
.proxyPass(“password”)
.setup();
A proxy acts as an intermediary between clients sending requests and server responding. The primary use of a proxy is to maintain privacy and encapsulation between multiple interactive systems.
A proxy can also add another layer of security on the web by acting as a firewall between Client and web servers. This is especially used when the websites that clients use have to be labeled as allowed or blocked based on the website content.
package HireQADemo;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertsDemo {
public static void main(String args[]) throws IOException {
System.setProperty(""webdriver.chrome.driver"", ""D:\\Data_Personal\\Software\\chromedriver_win32\\chromedriver.exe"");;
WebDriver driver = new ChromeDriver();
driver.get(""http://hireqa.co.in/test/basic_auth.php"");
// Handling Username alert
driver.switchTo().alert().sendKeys(""HireQA"");
driver.switchTo().alert().accept();
// Handling Password alert
driver.switchTo().alert().sendKeys(""HireQA"");
driver.switchTo().alert().accept();
}
}
In Selenium Webdriver Session ID is a unique number that is assigned to your web driver by server . Webdriver uses this session Id to interact with browser launched by them. So a browser window (eg Chrome) launched by a specific driver (chrome driver) will have a unique sessionId.
Since Eclipse is freeware tool so sometime it does not work as per your requirement and some point still point to old location in this case we can clean our project
When you face any inconsistency with Eclipse then clean your project or restart eclipse.
Step 1- Open Eclipse and Click on Project and Click on Clean
Step 2- Now you will get two options- You can select based on your choice
Clean all projects- This will clean the entire project on project explorer
1- Open Eclipse > Click on Window > Click on Preferences.
2- Click on General > Click on Appearance > Click on Color and Fonts > in right side Click on Basic.
3- Once you click on Basics > Now Select Text font and Click on Edit button.
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property;
System.setProperty(“webdriver.chrome.driver”, “path of the exe file\\chromedriver.exe”);
// Initialize browser
WebDriver driver=new ChromeDriver();
The term Gecko stands for a Web Browser engine that is inbuilt within Mozilla Firefox browser. Gecko driver acts as a proxy between Web Driver enabled clients(Eclipse, Netbeans, etc.) and Mozilla Firefox browser. In short, Gecko driver acts as a link between Selenium Web Driver tests and Mozilla Firefox browser.
Selenium uses W3C Webdriver protocol to send requests to GeckoDriver, which translates them into a protocol named Marionette. Firefox will understand the commands transmitted in the form of Marionette protocol and executes them.
System.setProperty(“webdriver.gecko.driver”, driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(“marionette”,true);
driver= new FirefoxDriver(capabilities);
or
FirefoxOptions options = new FirefoxOptions();
options.setLegacy(true);
1 :- WebDriver is an Interface(interface have only function prototype) in which by default all the method (public ,static)has to declared.
2:- WebDriver handles all activity which is related to Browser.
FireFoxDriver is a Class who has implemented all the method of WebDriver Interface.
1. SearchContext is the super most interface in selenium, which is extended by another interface called WebDriver.
2. All the abstract methods of SearchContext and WebDriver interfaces are implemented in RemoteWebDriver class.
3. All the browser related classes such as FirefoxDriver, ChromeDriver etc., extends the RemoteWebdriver class.
4. All the abstract methods of both the interfaces are implemented in RemoteWebDriver class which is extended by browser classes such as Firefox Driver, Chrome Driver etc.
We cannot write our code like this because we cannot create Object of an Interface. WebDriver is an interface.
WebDriver is an interface and all the methods which are declared in Webdriver interface are implemented by respective driver class.
But if we do upcasting,we can run the scripts in any browser .i.e running the same automation scripts in different browsers to achieve Runtime Polymorphism.
WebDriver is an interface, driver is a reference variable, FirefoxDriver() is a Constructor, new is a keyword, and new FirefoxDriver() is an Object.
- Selenium Remote Webdriver: It is an class that is used to execute the browser automation and to execute assessments in a distributed environment or on a remote computing device. In other words, It is a class that implements the WebDriver interface and this action is performed on the remote server. There are different driver classes for a browser such as ChromeDriver, FirefoxDriver, etc.
- Selenium Webdriver: It helps you to interact with browsers directly with the help of some automation scripts which includes a starting point, various variables with their binding values, and the source code. It is used to give support to various platforms, and its execution is little faster as compared to that of Selenium IDE or RC. It provides multiple client libraries which can be used in different programming languages like Python, C, Java, etc. which is used to build automation for the Selenium test.
Using id – #
Using class name – .
Using attribute – tagname[attribute=’value’]
Using multiple attribute – tagname[attribute1=’value’][attribute2=’value’]
Contains – * – tagname[attribute*=’value’]
Starts with – ^ – tagname[attribute^=’value’]
Ends with – $ – tagname[attribute$=’value’]
XPath starts-with() is a function used for finding the web element whose attribute value gets changed on refresh or by other dynamic operations on the webpage. In this method, the starting text of the attribute is matched to find the element whose attribute value changes dynamically.
Xpath=//label[starts-with(@id,’message’)]
The XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes.
Xpath=//td[text()=’UserID’]
XPath Contains() is a method which is used to find the value of those attribute which changes dynamically. For example, login information.
XPath=//tagname[contains(@attribute, 'value')]
XPath ends-with() method checks the ending text of an attribute and finds elements whose attribute changes dynamically on refresh. It has the following syntax as follows:
XPath= //tagname[ends-with(@attribute, 'value')]
By using clear() method
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.gmail.com”);
driver.findElement(By.xpath(“xpath_of_element1”)).sendKeys(“Software Testing Material Website”);
driver.findElement(By.xpath(“xpath_of_element1”)).clear();
isDisplayed()
WebElement radioBtn = driver.findElement (By.id(“gender-male”));
radioBtn.isDisplayed // this returns a Boolean value, if it returns true then said radio button is present on the webpage or it returns False.
isEnabled()
radioBtn.isEnabled() // this returns a Boolean value, if it returns true then said radio button is enabled on the webpage or it returns False
isSelected()
radioBtn.isSelected() // this returns a Boolean value, if it returns true then said radio button is selected or it returns False
Selenium already provides Select class that has some predefined method which help is a lot while working with Dropdown.
WebElement month_dropdown=driver.findElement(By.id(“month”));
Select month=new Select(month_dropdown);
month.selectByIndex(4);
month.selectByValue(“5”);
month.selectByVisibleText("Aug");
Select month=new Select(month_dropdown);
WebElement first_value=month.getFirstSelectedOption();
String value=first_value.getText();
WebElement month_dropdown=driver.findElement(By.id(""month""));
Select month=new Select(month_dropdown);
List dropdown=month.getOptions();
for(int i=0;i<dropdown.size();i++){
String drop_down_values=dropdown.get(i).getText();
System.out.println(""dropdown values are ""+drop_down_values);
}
The bootstrap dropdown is enhanced part of dropdown where you will deal with UL and LI tag of HTML.
List list = driver.findElementsByXPath(""//ul[@class='dropdown-menu']//li/a"");
// We are using enhanced for loop to get the elements
for (WebElement ele : list)
{
// for every elements it will print the name using innerHTML
System.out.println(""Values "" + ele.getAttribute(""innerHTML""));
// Here we will verify if link (item) is equal to Java Script
if (ele.getAttribute(""innerHTML"").contains(""JavaScript"")) {
// if yes then click on link (iteam)
ele.click();
// break the loop or come out of loop
break;
}
if(dropdown.isMultiple())
{sysout(""multiple option is allowed"")}
Returns TRUE if the drop-down element allows multiple selections at a time; FALSE if otherwise.
dropdown.deSelectAll();
We use click() method in Selenium to click on the hyperlink
driver.findElement(By.linkText(“Software Testing Material Website”)).click();
An exception is thrown. We need to pass HTTP protocol within driver.get() method.
Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)
driver.get(): To open an URL and it will wait till the whole page gets loaded
driver.navigate.to(): To navigate to an URL and It will not wait till the whole page gets loaded
driver.navigate().forward();
driver.navigate().back();
driver.navigate().refresh();
driver.navigate().to(“url”);
Action Class in Selenium is a built-in feature provided by the selenium for handling keyboard and mouse events. It includes various operations such as multiple events clicking by control key, drag and drop events and many more.
clickAndHold() – Clicks (without releasing) at the current mouse location.
contextClick()– Performs a context-click at the current mouse location. (Right Click Mouse Action)
doubleClick() Performs a double-click at the current mouse location.
dragAndDrop(source, target) – Performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.
dragAndDropBy(source, x-offset, y-offset) – Performs click-and-hold at the location of the source element, moves by a given offset, then releases the mouse.
keyDown(modifier_key) – Performs a modifier key press. Does not release the modifier key – subsequent interactions may assume it’s kept pressed.
modifier_key – any of the modifier keys (Keys.ALT, Keys.SHIFT, or Keys.CONTROL)
keyUp(modifier _key) – Performs a key release.
moveByOffset(x-offset, y-offset) – Moves the mouse from its current position (or 0,0) by the given offset.
moveToElement(toElement) – Moves the mouse to the middle of the element.
release() – Releases the depressed left mouse button at the current mouse location
sendKeys(onElement, charsequence) – Sends a series of keystrokes onto the element.
WebElement ele = driver.findElement(By.xpath(“xpath”));
//Create object ‘action’ of an Actions class
Actions action = new Actions(driver);
//Mouseover on an element
action.moveToElement(ele).perform();
Actions builder = new Actions(driver);
Action seriesOfActions = builder
.moveToElement(txtUsername)
.click()
.keyDown(txtUsername, Keys.SHIFT)
.sendKeys(txtUsername, ""hello"")
.keyUp(txtUsername, Keys.SHIFT)
.doubleClick(txtUsername)
.contextClick()
.build();
seriesOfActions.perform() ;
Actions action = new Actions(driver);
action.clickAndHold(slider).moveByOffset(50,0).release();
Move To Element:
Actions builder=new Actions(driver);
WebElement ele=driver.findElement(By.xpath("".//*[@id='autosuggest']/ul/li[2]/a""));
builder.moveToElement(ele).build().perform();
builder.click(ele).build().perform();
Right Click on Element:
Actions act=new Actions(driver);
act.contextClick(driver.findElement(By.linkText(“Gujarati”))).perform();
Key Down:
Actions act=new Actions(driver);
act.contextClick(driver.findElement(By.linkText(""Gujarati""))).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
Approach 1:
Actions act=new Actions(driver);
// find element which we need to drag
WebElement drag=driver.findElement(By.xpath("".//*[@id='draggable']""));
// find element which we need to drop
WebElement drop=driver.findElement(By.xpath("".//*[@id='droppable']""));
// this will drag element to destination
act.dragAndDrop(drag, drop).build().perform();
Approach 2:
Actions act=new Actions(driver);
// find element which we need to drag
WebElement source=driver.findElement(By.xpath(""(//span[text()='Thrillers'])[1]""));
WebElement destination=driver.findElement(By.xpath(""(//span[text()='History'])[2]""));
// it will click and hold the triller box and move to element will move cursor to history in another box and then release
act.clickAndHold(source).pause(2000).moveToElement(destination).release().build().perform();
Scenario 1: Tooltip is implemented using the ""title"" attribute
WebElement github = driver.findElement(By.xpath("".//*[@class='soc-ico show-round']/a[4]""));
//get the value of the ""title"" attribute of the github icon
String actualTooltip = github.getAttribute(""title"");
Scenario 2: Tooltip is implemented using a jQuery plugin.
String expectedTooltip = ""What's new in 3.2"";
driver.get(baseUrl);
WebElement download = driver.findElement(By.xpath("".//*[@id='download_now']""));
Actions builder = new Actions (driver);
builder.clickAndHold().moveToElement(download);
builder.moveToElement(download).build().perform();
WebElement toolTipElement = driver.findElement(By.xpath("".//*[@class='box']/div/a""));
String actualTooltip = toolTipElement.getText();
System.out.println(""Actual Title of Tool Tip ""+actualTooltip);
if(actualTooltip.equals(expectedTooltip)) {
System.out.println(""Test Case Passed"");
}
Web-Based alert and Java Script alerts are same so do not get confused.
Alert Interface has some methods-
1- accept()- Will click on the ok button when an alert comes.
2- dismiss()- Will click on cancel button when an alert comes.
//Captured Alert Text (Actual Text)
String actualAlertMessage = driver.switchTo().alert().getText();
//Accept the alert (Click OK)
driver.switchTo().alert().accept();
//Accept the alert (Click Cancel)
driver.switchTo().alert().dismiss();
//Send “Hire QA” to Alert’s text box
driver.switchTo().alert().sendKeys(“Hire QA”);
iFrame is a HTML document embedded inside an HTML document. iFrame is defined by an tag in HTML. With this tag, you can identify an iFrame while inspecting the HTML tree.
To Switch between iFrames we have to use the driver’s switchTo().frame command.
We can use the switchTo().frame() in three ways:
- switchTo.frame(int frameNumber): Pass the frame index and driver will switch to that frame.
- switchTo.frame(string frameName): Pass the frame element Name or ID and driver will switch to that frame.
- switchTo.frame(WebElement frameElement): Pass the frame web element and driver will switch to that frame.
//Switch by frame name
driver.switchTo().frame(“iframe1”);
//Switch by frame ID
driver.switchTo().frame(“IF1”);
//First find the element using any of locator stratedgy
WebElement iframeElement = driver.findElement(By.id(“IF1”));
//switch to frame by using frame element
driver.switchTo().frame(iframeElement);
//Switch back to the main window
driver.switchTo().defaultContent();
// It will return the parent window name as a String
String parent=driver.getWindowHandle();
// This will return the number of windows opened by Webdriver and will return Set of St//rings
Sets1=driver.getWindowHandles();
// Now we will iterate using Iterator
Iterator I1= s1.iterator();
while(I1.hasNext())
{
String child_window=I1.next();
// Here we will compare if parent window is not equal to child window then we will close
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());
driver.close();
}
}
// once all pop up closed now switch to parent window
driver.switchTo().window(parent);
}
}
//No.of Columns
List col = wd.findElements(By.xpath(“.//*[@id=\”leftcontainer\”]/table/thead/tr/th”));
System.out.println(“No of cols are : ” +col.size());
//No.of rows
List rows = wd.findElements(By.xpath(“.//*[@id=’leftcontainer’]/table/tbody/tr/td[1]”));
System.out.println(“No of rows are : ” + rows.size());
Fetch 3rd row and 2nd cell data
———————————————-
//To find third row of table
WebElement tableRow = baseTable.findElement(By.xpath(“//*[@id=\”leftcontainer\”]/table/tbody/tr[3]”));
String rowtext = tableRow.getText();
System.out.println(“Third row of table : “+rowtext);
//to get 3rd row’s 2nd column data
WebElement cellIneed = tableRow.findElement(By.xpath(“//*[@id=\”leftcontainer\”]/table/tbody/tr[3]/td[2]”));
String valueIneed = cellIneed.getText();
System.out.println(“Cell value is : ” + valueIneed);
//No. of Columns
List col = wd.findElements(By.xpath("".//*[@id='leftcontainer']/table/thead/tr/th""));
System.out.println(""Total No of columns are : "" +col.size());
//No.of rows
List rows = wd.findElements(By.xpath ("".//*[@id='leftcontainer']/table/tbody/tr/td[1]""));
System.out.println(""Total No of rows are : "" + rows.size());
for (int i =1;ir)
{
r=m;
}
}
System.out.println(""Maximum current price is : ""+ r);
Desired Capabilities are needed because every Testing scenario should be executed on some specific testing environment. The testing environment can be a web browser, Mobile device, mobile emulator, mobile simulator, etc. The Desired Capabilities Class helps us to tell the webdriver, which environment we are going to use in our test script.
//it is used to define IE capability
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE");
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
//it is used to initialize the IE driver
WebDriver driver = new InternetExplorerDriver(capabilities);
ChromeOptions is a class that can be used to manipulate capabilities specific to ChromeDriver. For instance, you can disable Chrome extensions with:
ChromeOptions options = new ChromeOptions()
options.addArgument(“disable-extensions”);
ChromeDriver driver = new ChromeDriver(options);
DesiredCapabilities can also be used to manipulate a ChromeDriver session. To change individual web driver properties, DesiredCapabilities class provides key-value pairs.
But, ChromeOptions supports limited clients whereas DesiredCapabilities supports a vast number of clients. ChromeOptions is supported by Java and other languages. DesiredCapabilities is available in Java, but its use is deprecated. When working with a client library, like Selenium Ruby Client, the ChromeOption class will not be available and DesiredCapabilities will have to be used.
DesiredCapabilities are commonly used with Selenium Grid, for parallel execution of test cases on different browsers. However, one can use both DesiredCapabilities and ChromeOptions using merge:
DesiredCapabilities capabilities = new DesiredCapabilities();
options = new ChromeOptions();
options.merge(capabilities);
driver = new ChromeDriver(options);
driver.get(""http://www.google.co.in/"");
List links=driver.findElements(By.tagName(""a""));
System.out.println(""Total links are ""+links.size());
for(int i=0;i<links.size();i++)
{
WebElement ele= links.get(i);
String url=ele.getAttribute(""href"");
verifyLinkActive(url);
----------------------------------------------
public static void verifyLinkActive(String linkUrl)
{
try
{
URL url = new URL(linkUrl);
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==200)
{
System.out.println(linkUrl+"" - ""+httpURLConnect.getResponseMessage());
}
if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)
{
System.out.println(linkUrl+"" - ""+httpURLConnect.getResponseMessage() + "" - ""+ HttpURLConnection.HTTP_NOT_FOUND);
}
} catch (Exception e) {
}
}
During test execution, the Selenium WebDriver has to interact with the browser all the time to execute given commands. At the time of execution, it is also possible that, before current execution completes, someone else starts execution of another script, in the same machine and in the same type of browser.
In such situation, we need a mechanism by which our two different executions should not overlap with each other. This can be achieved using Session Handling in Selenium.
To work with Basic Authentication pop-up (which is a browser dialogue window), you just need to send the user name and password along with the application URL.
#1 (Chrome & Firefox)
By passing user credentials in URL. Its simple, append your username and password with the URL.
e.g., http://Username:Password@SiteURL
http://rajkumar:myPassword@www.softwaretestingmaterial.com
#2 (IE)
First create AutoIt script as below and save it as basicauth.au3
To pass user name and password
WinWaitActive(“Windows Security”)
Send(“admin”)
Send(“{TAB}”)
Send(“admin”)
Send(“{ENTER}”)
————————————————–
try {
Runtime.getRuntime().exec(“G:/basicauth.exe”);
} catch (Exception e) {
e.printStackTrace();
}
//Create an object of File class to open xlsx file
File file = new File(filePath+""\\""+fileName);
//Create an object of FileInputStream class to read excel file
FileInputStream inputStream = new FileInputStream(file);
Workbook workBook = null;
//Find the file extension by splitting file name
String fileExtensionName = fileName.substring(fileName.indexOf("".""));
//Check condition if the file is xlsx file
if(fileExtensionName.equals("".xlsx"")){
workBook = new XSSFWorkbook(inputStream);
} else if(fileExtensionName.equals("".xls"")){
workBook = new HSSFWorkbook(inputStream);
}
//Read sheet inside the workbook by its name
Sheet sheet = workBook.getSheet(sheetName);
//Find number of rows in excel file
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
//Create a loop over all the rows of excel file to read it
for (int i = 0; i < rowCount+1; i++) {
Row row = sheet.getRow(i);
//Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++) {
//Print Excel data in console
System.out.print(row.getCell(j).getStringCellValue()+""|| "");
File file = new File(filePath+""\\""+fileName);
FileInputStream inputStream = new FileInputStream(file);
Workbook workBook = null;
workBook = new XSSFWorkbook(inputStream);
Sheet sheet = workBook .getSheet(sheetName);
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
Row row = sheet.getRow(0);
//Create a new row and append it at last of sheet
Row newRow = sheet.createRow(rowCount+1);
for(int j = 0; j < row.getLastCellNum(); j++){
Cell cell = newRow.createCell(j);
cell.setCellValue(dataToWrite[j]);
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(file);
workBook.write(outputStream);
outputStream.close();
Create a new file and give file name as Object_Repo (depends on you)with extension .properties
// Specify the file location I used . operation here because
//we have object repository inside project directory only
File src=new File("".Object_Repo.properties"");
// Create FileInputStream object
FileInputStream fis=new FileInputStream(src);
// Create Properties class object to read properties file
Properties pro=new Properties();
// Load file so we can use into our script
pro.load(fis);
System.out.println(""Property class loaded"");
// Open FirefoxBrowser
WebDriver driver=new FirefoxDriver();
// Maximize window
driver.manage().window().maximize();
// Pass application
driver.get(""http://www.facebook.com"");
// Enter username here I used keys which is specified in Object repository.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty(""facebook.login.username.xpath""))).
sendKeys(""Selenium@gmail.com"");
Selenium Webdriver is limited to Testing your applications using Browser. To use Selenium Webdriver for Database Verification you need to use the JDBC (“Java Database Connectivity”).
JDBC (Java Database Connectivity) is a SQL level API that allows you to execute SQL statements. It is responsible for the connectivity between the Java Programming language and a wide range of databases. The JDBC API provides the following classes and interfaces
Driver Manager
Driver
Connection
Statement
ResultSet
SQLException
//You also need to load the JDBC Driver using the code
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(dbUrl,username,password);
ex URL: jdbc:mysql://localhost:3036/emp
"//You can use the Statement Object to send queries.
Statement stmt = con.createStatement();
//Once the statement object is created use the executeQuery method to execute the SQL queries:
ResultSet rs = stmt.executeQuery(select * from employee;);
while (rs.next()){
String myName = rs.getString(1);
String myAge = rs.getString(2);
System. out.println(myName+"" ""+myAge);
}
// closing DB Connection
con.close();
Results from the executed query are stored in the ResultSet Object.
JAVA provides loads of advanced methods to process the results:
- String getString() – to fetch the string type data from resultset.
- int getInt() – to fetch the integer type data from resultset
- double getDouble() – to fetch double type data from resultset
- Date getDate() – to fetch Date type object from resultset
- boolean next() – moves to the next record in the resultset
- boolean previous() – move to the previous record in the resultset
- boolean first() – moves to the first record in the resultset
- boolean last() – moves to the last record in the resultset
- bolean absolute – to move to specific record in the resultset
//Convert web driver object to TakeScreenshot
TakesScreenshot screenshot=((TakesScreenshot)driver);
//Call getScreenshotAs method to create image file
File SrcFile=screenshot.getScreenshotAs(OutputType.FILE);
//Copy file to Desired Location
FileUtils.copyFile(SrcFile, DestFilePath);
10 seconds ImplicitlyWait for a element is not a valid statement. Explicit Wait of 5 second you have to put for a certain state/behavior of the element (e.g. element_to_be_clickable). If the element doesn’t shows that behavior within the defined time slot Selenium will throw an exception.
Using explicit wait/implicit wait is the best practice, Lets check what actually the explicit wait,Thread.sleep(), Implicit wait’s working logic.
Explicit wait: An explicit waits is a kind of wait for a certain condition to occur before proceeding further in the code.
Implicit wait: 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
Thread.sleep() In sleep code will always wait for mentioned seconds in side the parentheses even in case working page is ready after 1 sec. So this can slow the tests.
System.setProperty(""webdriver.chrome.driver"", ""D:\\softwares\\chromedriver_win32\\chromedriver.exe"");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get(""https://mail.google.com/"");
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
//driver.findElement(By.linkText(""www.facebook.com"")).sendKeys(selectLinkOpeninNewTab);
driver.findElement(By.linkText(""www.facebook.com"")).sendKeys(Keys.CONTROL +""t"");
----------------------------------------------------------------------------
WebDriver driver = new ChromeDriver();
driver.get(""http://yahoo.com"");
((JavascriptExecutor)driver).executeScript(""window.open()"");
ArrayList tabs = new ArrayList(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get(""http://google.com"");
1. Use Actions() method
WebElement element = driver.findElement(By(“element_path”));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();
————————————————————————-
2. Use Waits to let the page load completely before the click is performed
driver.manage().timeouts().implicitlywait(15 TimeUnit.seconds)
———————————————————————–
3. The element is not clickable because of a Spinner/Overlay on top of it:
By loadingImage = By.id(“loading image ID”);
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.invisibilityOfElementLocated(loadingImage));
WebElement element = driver.findElement(By.id(“gbqfd”));
JavascriptExecutor js= (JavascriptExecutor)driver;
js.executeScript(“arguments[0].click();”, element);
driver.get(“https://www.hireqa.co.in”);
List list= driver.findElements(By.className(“store-name”));
System.out.println(list.size());
for (WebElement webElement : list) {
String name = webElement.getText();
System.out.println(name);
}
JavascriptExecutor js = ((JavascriptExecutor)driver);
js.executeScript(""window.scrollTo(0, document.body.scrollHeigh)"").;
js.executeScript(""arguments[0].scrollIntoView(true);"",element);
js.executeScript(""window.scrollBy(0,500)"");
String output = driver.findElement(By.xpath(“/html/body/div[1]/div[5]/div/div/div[1]/div[2]/div[1]/div”)).getText();
File DestFile= new File(“extractedFilePath”);
FileUtils.writeStringToFile(DestFile, output);
Robot robot = new Robot();
StringSelection filepath = new StringSelection(""file path"");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filepath,null);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.acceptInsecureCert();
cap.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
ChromeOptions options = new ChromeOptions();
options.merge(cap);
WebDriverManager.chromeDriver.setup();
WebDriver driver = new ChromeDriver(options);
----------------------------------------------------------
FirefoxOption options = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
options.setProfile(profile);
WebDriverManager.firefoxDriver.setUp();
WebDriver driver = new FirefoxDriver(options);
System.out.println(((RemoteWebDriver)driver).getCapabilities().toString();
WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully hence the default polling time for ExplicitWait is 500 milliseconds.
An implicit wait is to tell Web Driver 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 Web Driver object instance until it changed again.
driver.manage () is a method that returns instance of options interface, now the options interface has method window () that returns instance of window interface, this window interface has method maximize () which maximizes the window.
get() is used to navigate particular URL (website) and wait till page load. driver. navigate() is used to navigate to particular URL and does not wait to page load. It maintains browser history or cookies to navigate back or forward.
Both click () and submit () both are used to click Button in Web page. Selenium WebDriver has one special method to submit any form and that method name Is submit (). submit () method works same as clicking on submit button. You can use .click () method to click on any button. There is no restriction for click buttons.
Solution 1: Refreshing the web page
Solution 2: Using Try Catch Block
Solution 3: Using Explicit Wait
Solution 4: Using PageFactory
We could avoid StaleElementException using POM. In POM, we use initElements() method which loads the element but it won’t initialize elements. initElements() takes latest address. It initializes during run time when we try to perform any action on an element. This process is also known as Lazy Initialization.
Here we are creating an object of the ChromeDriver() by taking reference to the WebDriver interface.
ABSTRACTION In Page Object Model design pattern, we write locators (such as id, name, xpath etc.,) in a Page Class. We utilize these locators in tests but we can’t see these locators in the tests. Literally we hide the locators from the tests. Abstraction is the methodology of hiding the implementation of internal details and showing the functionality to the users. |
INTERFACE WebDriver driver = new FirefoxDriver(); we are initializing Firefox browser using Selenium WebDriver. It means we are creating a reference variable (driver) of the interface (WebDriver) and creating an Object. Here WebDriver is an Interface as mentioned earlier and FirefoxDriver is a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract. |
INHERITANCE We create a Base Class in the Framework to initialize WebDriver interface, WebDriver waits, Property files, Excels, etc., in the Base Class. We extend the Base Class in other classes such as Tests and Utility Class. Extending one class into other class is known as Inheritance. |
POLYMORPHISM Combination of overloading and overriding is known as Polymorphism. We will see both overloading and overriding below. Polymorphism allows us to perform a task in multiple ways. |
METHOD OVERLOADING We use implicit wait in Selenium. Implicit wait is an example of overloading. In Implicit wait we use different time stamps such as SECONDS, MINUTES, HOURS etc., A class having multiple methods with same name but different parameters is called Method Overloading |
METHOD OVERLOADING We use implicit wait in Selenium. Implicit wait is an example of overloading. In Implicit wait we use different time stamps such as SECONDS, MINUTES, HOURS etc., A class having multiple methods with same name but different parameters is called Method Overloading |
ENCAPSULATION In POM classes, we declare the data members using @FindBy and initialization of data members will be done using Constructor to utilize those in methods. Encapsulation is a mechanism of binding code and data together in a single unit. |
ChromeOptions options = new ChromeOptions();
options.addArguments(“disable-infobars”);
WebDriver player = new ChromeDriver(options);
The parallel attribute of suite tag can accept four values:
tests – All the test cases inside tag of testng.xml file will run parallel
classes – All the test cases inside a java class will run parallel
methods – All the methods with @Test annotation will execute parallel
instances – Test cases in same instance will execute parallel but two methods of two different instances will run in different thread.
By adding the exclude tag in the testng.xml
WebDriver driver = new HtmlUnitDriver()
Fastest implementation of WebDriver compared to other browsers
A pure Java solution and so it is platform independent.
Supports JavaScript
It allows you to choose other browser versions to run your scripts.
JavaScript In HtmlUnit Driver: HtmlUnitDriver uses Rhino JavaScript engine. Other browsers are using separate JavaScript engine. So the test results may differ when compared to other browsers when you test JavaScript applications using HtmlUnit. By default, JavaScript is disabled in HtmlUnitDriver. Don’t worry, there is a way to enable it. |
Enabling JavaScript while initializing the HtmlUnitDriver: HtmlUnitDriver driver = new HtmlUnitDriver(true); Setting ‘setJavascriptEnabled’ to true HtmlUnitDriver driver = new HtmlUnitDriver(); setJavascriptEnabled(true); |
The Robot class helps in providing control over the mouse and keyboard devices. It includes:
- KeyPress()
Invoked when you want to press any key
- KeyRelease()
Invoked to release the pressed key on the keyboard
- MouseMove()
Invoked to move the mouse pointer in the X and Y coordinates
- MousePress()
Invoked to press the left button of the mouse
String PROXY = "199.201.125.147:8080";
org.openqa.selenium.Proxy proxy = new.org.openqa.selenium.Proxy();
proxy.setHTTPProxy(Proxy)
.setFtpProxy(Proxy)
.setSslProxy(Proxy)
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new FirefoxDriver(cap);
JavaScriptExecutor is an interface which provides a mechanism to execute Javascript through the Selenium WebDriver. It provides “executescript” and “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window. An example of that is:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
public static void main(String[] args)
{
String baseUrl = “https://www.facebook.com”;
WebDriver driver = new FirefoxDriver();
driver.get("baseUrl");
WebElement txtUserName = driver.findElement(By.id(“Email”);
Actions builder = new Actions(driver);
Action seriesOfActions = builder
.moveToElement(txtUerName)
.click()
.keyDown(txtUserName, Keys.SHIFT)
.sendKeys(txtUserName, “hello”)
.keyUp(txtUserName, Keys.SHIFT)
.doubleClick(txtUserName);
.contextClick();
.build();
seriesOfActions.perform();
}
To maximize the size of browser window, you can use the following piece of code:
driver.manage().window().maximize(); – To maximize the window
To resize the current window to a particular dimension, you can use the setSize() method. Check out the below piece of code:
System.out.println(driver.manage().window().getSize());
Dimension d = new Dimension(420,600);
driver.manage().window().setSize(d);
To set the window to a particular size, use window.resizeTo() method. Check the below piece of code:
((JavascriptExecutor)driver).executeScript(“window.resizeTo(1024, 768);”);
To upload a file we can simply use the command element.send_keys(file path). But there is a prerequisite before we upload the file. We have to use the html tag: ‘input’ and attribute type should be ‘file’.
element = driver.find_element_by_id(”uploaded_file")
element.send_keys("C:myfile.txt")
We can enter/ send text without using sendKeys() method. We can do it using JavaScriptExecutor.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById(‘Login').value=Test text without sendkeys");
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(**username**, **password**));
Since there will be popup for logging in, we need to use the explicit command and verify if the alert is actually present. Only if the alert is present, we need to pass the username and password credentials.
@Test(invocationCount=?) is a parameter that indicates the number of times this method should be invoked.
@Test(threadPoolSize=?) is used for executing suites in parallel. Each suite can be run in a separate thread.
To specify how many times @Test method should be invoked from different threads, you can use the attribute threadPoolSize along with invocationCount.
@Test(threadPoolSize = 3, invocationCount = 10)
public void testServer() {
}
This can be done by simulating key presses on the focused element. One way is to perform “actions” on the web driver object:
new Actions(webDriver).sendKeys(“some text”).perform();
An alternative way is to switch to the active element first, and send keys to it directly:
webDriver.switchTo().activeElement().sendKeys(“some text”);
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class CurrentDateTimeExample1 {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
}
}
// identify text
WebElement t = driver.findElement(By.tagName("h1"));
//obtain color in rgba
String s = t.getCssValue("color");
// convert rgba to hex
String c = Color.fromString(s).asHex();
System.out.println("Color is :" + s);
System.out.println("Hex code for color:" + c);
// identify element
WebElement l=driver.findElement(By.className("fb_logo _8ilh img"));
// getAttribute() to get src value
String value = l.getAttribute("src");
System.out.println("Src attribute is: "+ value);
// identify element
WebElement l=driver.findElement(By.cssSelector(".gsc-input"));
//activeElement() to verify element focused
if(l.equals(driver.switchTo().activeElement()))
System.out.println("Element is focused");
else
System.out.println("Element is not focused");
We can click on an element which is hidden with Selenium webdriver. The hidden elements are the ones which are present in the DOM but not visible on the page. Mostly the hidden elements are defined by the CSS property style=”display:none;”. In case an element is a part of the form tag, it can be hidden by setting the attribute type to the value hidden.
Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method. The commands to be run are passed as arguments to the method.
Now let us enter some text inside the hidden text box.
// Javascript executor class with executeScript method
JavascriptExecutor j = (JavascriptExecutor) driver;
// identify element and set value
j.executeScript ("document.getElementById('text-box').value='Selenium';");
String s = (String) j.executeScript("return document.getElementById('text-box').value");
System.out.print("Value entered in hidden field: " +s);
We can perform double click on elements in Selenium with the help of Actions class. In order to perform the double click action we will use moveToElement() method, then use doubleClick() method. Finally use build().perform() to execute all the steps.
// doubleClick() method for double click to an element after moving to
//element to with the moveToElement()
Actions a = new Actions(driver);
a.moveToElement(driver.findElement(By.xpath(“input[@type=’text’]))).
doubleClick().
build().perform();
We can click on a button with across browsers with Selenium webdriver. First of all we need to identify the element with the help of locators like xpath or css, then apply sendKeys() method where the path of the file to be uploaded is passed.
// identify element
WebElement l=driver.findElement(By.cssSelector("input[type='file']"));
// file path passed with sendkeys()
l.sendKeys("C:\Users\ghs6kor\Pictures\Desert.jpg");
The following are the two different ways you can type text into the text box fields in Selenium:
Using sendKeys():
– driver.findElement().sendKeys();
Using JavascriptExecutor:
– JavascriptExecutor jse = (JavascriptExecutor)driver;
– jse.executeScript(“document.getElementById(“username”).setAttribute(‘value’,’hireqa’)”);
Different types of verification points in Selenium are:
To check element is present
if(driver.findElements(By.Xpath(“value”)).size()!=0){
System.out.println(“Element is present”);
}else{
System.out.println(“Element is absent”);
}
To check element is visible
if(driver.findElement(By.Id(“submit”)).isDisplayed()){
System.out.println(“Element is visible”);
}else{
System.out.println(“Element is visible”);
}
To check element is enabled
if(driver.findElement(By.Id(“submit”)).isEnabled()){
System.out.println(“Element is enabled”);
}else{
System.out.println(“Element is disabled”);
}
To check text is present
if(driver.getPageSource().contains(“Text”)){
System.out.println(“Text is present”);
}else{
System.out.println(“Text is not present”);
}
We can pause test execution for 5 seconds by using the wait command.
driver.wait(5);
java -jar selenium-server.jar -htmlSuite “*firefox” “localhost” “C:\mytestsuite.html” “C:\results.html”
if(driver.findElements(Locator).size()>0
{
return true
}else
{
return false
}
}
driver.getPageSource().contains(“TEXT that you want to see on the page”);
This function will fetch message on Pop-up
public static String getPopupMessage(final WebDriver driver) {
String message = null;
try {
Alert alert = driver.switchTo().alert();
message = alert.getText();
alert.accept();
} catch (Exception e) {
message = null;
}
System.out.println("message"+message);
return message;
}
This function will Canceling pop-up in Selenium-WebDriver
public static String cancelPopupMessageBox(final WebDriver driver) {
String message = null;
try {
Alert alert = driver.switchTo().alert();
message = alert.getText();
alert.dismiss();
} catch (Exception e) {
message = null;
}
return message;
}
public static String tooltipText(WebDriver driver, By locator){
String tooltip = driver.findElement(locator).getAttribute("title");
return tooltip;
}
public static void selectRadioButton(WebDriver driver, By locator, String value){
List select = driver.findElements(locator);
for (WebElement element : select)
{
if (element.getAttribute("value").equalsIgnoreCase(value)){
element.click();
}
}
public static void selectCheckboxes(WebDriver driver, By locator,String value)
{
List abc = driver.findElements(locator);
List list = new ArrayListArrays.asList(value.split(",")));
for (String check : list){
for (WebElement chk : abc){
if(chk.getAttribute("value").equalsIgnoreCase(check)){
chk.click();
}}}}
public static void downloadFile(String href, String fileName) throws Exception{
URL url = null;
URLConnection con = null;
int i;
url = new URL(href);
con = url.openConnection();
// Here we are specifying the location where we really want to save the file.
File file = new File(".//OutputData//" + fileName);
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
bis.close();
}
- Ajax stands for Asynchronous JavaScript and XML. Ajax is a new technology for creating for faster and more interactive web applications. What ajax does is: Update a web page without reloading/refresh it.
- Google search is a best example of ajax. In case of google search, you simply type any keyword in search bar and just below the search bar a suggestion box with matching suggestions appears instantly, this is ajax.
- We can handle ajax in Selenium WebDriver with the use of Explicit Wait command.
// Set Driver path
System.setProperty("webdriver.chrome.driver", "C:\\drivers\chromedriver.exe");
WebDriver driver=new ChromeDriver();
//open google
driver.get("https://www.google.com");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//enter selenium in search box
driver.findElement(By.name("q")).sendKeys("selenium ");
//wait for suggestions
WebDriverWait wait=new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.className("sbtc")));
WebElement list=driver.findElement(By.className("sbtc"));
List rows=list.findElements(By.tagName("li"));
for(WebElement elem:rows) {
System.out.println(elem.getText());
}