To handle alert window in Selenium Webdriver we have predefined Interface known as Alert.
Alert Interface has some methods-
There are the four methods that we would be using along with the Alert interface:
void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
String getText() – The getText() method returns the text displayed on the alert box.
void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
Note - Since alert is separate window so before using these methods we have to switch to alert window using "switchTo()" method.
public static void handleAlert(WebDriver ldriver){
if(isAlertPresent(ldriver)){
Alert alert = ldriver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
}
public static boolean isAlertPresent(WebDriver ldriver){
try{
driver.switchTo().alert();
return true;
}
catch(NoAlertPresentException ex){
return false;
}
}
public void switchToFrame(int frame) {
try {driver.switchTo().frame(frame);
System.out.println("Navigated to frame with id " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + frame
+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with id " + frame
+ e.getStackTrace());
}
}
Syntax for switching a frame: driver.switchTo().frame(WebElement frameElement);
Description: Select a frame using its previously located WebElement.
Parameters: frameElement - The frame element to switch to.
Returns: Driver focused on the given frame (current frame).
Throws: NoSuchFrameException - If the given element is neither an iframe nor a frame element.
StaleElementReferenceException - If the WebElement has gone stale.
Below is an example with a code which sends an Element to the switch.
public void switchToFrame(WebElement frameElement) {
try {
if (isElementPresent(frameElement)) {
driver.switchTo().frame(frameElement);
System.out.println("Navigated to frame with element "+ frameElement);
}
else {
System.out.println("Unable to navigate to frame with element "+ frameElement);
}
}
catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with element " + frameElement
+ e.getStackTrace());
} catch (StaleElementReferenceException e) {
System.out.println("Element with " + frameElement
+ "is not attached to the page document" + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with element "
+ frameElement + e.getStackTrace());
}
}
Some times when there are multiple frames (i.e. frame inside a frame), we need to first switch to the parent frame and then we move to the child frame. Below is the code snippet to work with multiple frames.
public void switchToFrame(String ParentFrame, String ChildFrame) {
try {
driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);
System.out.println("Navigated to innerframe with id " + ChildFrame
+ "which is present on frame with id" + ParentFrame);
}
catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " +ParentFrame + " or "
+ ChildFrame + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to innerframe with id "
+ ChildFrame + "which is present on frame with id"
+ ParentFrame + e.getStackTrace());
}
}
After working with the frames, main important is to come back to the web page. if we don’t switch back to the default page, driver will throw an exception. Below is the code snippet to switch back to the default content.
public void switchtoDefaultFrame() {
try {
driver.switchTo().defaultContent();
System.out.println("Navigated back to webpage from frame");
}
catch (Exception e) {
System.out.println("unable to navigate back to main webpage from frame"
+ e.getStackTrace());
}
}
package com.javabykiran; import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShotEx {
// opens a Firefox browser
WebDriver driver = new FirefoxDriver();
String CONFIG = "Y"; // this you can bring later from property file
// opening of url
public void captureScreenshot(String filename) throws IOException {
driver.get("http://www.javabykiran.com/selenium/demo/");
// take screen shots
if (CONFIG.equals("Y")) { // just showing check
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile,
new File(System.getProperty("user.dir") + "//screenshots//" + filename + ".jpg"));
}
}
public static void main(String[] args) {
ScreenShotEx ex = new ScreenShotEx();
try {
ex.captureScreenshot("abc");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Select is a class which is provided by Selenium to perform multiple operations on DropDown object and Multiple Select object. This class can be found under the Selenium’s Support.UI. Select package.
The below is the sample html code of Dropdown.
Webdriver code for Selecting a Value using select.selectByValue(Value):
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
publicclass SelectExample {
publicstaticvoid main(String[] args) {
WebDriver wd = new FirefoxDriver();
wd.get("http://www.javabykiran.com/selenium/demo/");
wd.manage().window().maximize();
wd.findElement(By.id("email")).sendKeys("kiran@gmail.com");
wd.findElement(By.id("password")).sendKeys("123456");
wd.findElement(By.xpath(".//*[@id='form']/div[3]/div/button")).click();
wd.findElement(By.xpath("//span[contains(.,'Users')]")).click();
wd.findElement(By.xpath("//button[contains(.,'Add User')]")).click();
WebElement element = wd.findElement(By.xpath("//select[contains(@ class,'form-control')]"));
Select se = new Select(element);
se.selectByValue("Delhi");
}
}
It is almost the same as “selectByValue” but the only difference is that we provide the ‘index number of the option’ here rather than ‘option text’. It takes a parameter of int which is the index value of “Select element” and it returns nothing.
Syntax:
WebElement element = wd.findElement(By.xpath("//select[contains(@class,'form- control')]"));
Select se = new Select(element);
se.selectByIndex("2");
Syntax:
WebElement element = wd.findElement(By.xpath("//select[contains(@ class,'form-control')]"));
Select se = new Select(element);
se.selectByVisibleText("HP");
A HTTP cookie comprises of information about the user and their preferences.
It stores information using a key-value pair. It is a small piece of data sent from Web Application and stored in Web Browser even while the user is browsing that website.
Each cookie is associated with a name, value, domain, path, expiry and the status of the data whether it is secured or not. In order to validate a client, a server parses all of these values in a cookie. When testing a web application using selenium web driver, you may need to create, update or delete a cookie.
For example, when automating Online Shopping Application, you many need to automate test scenarios like place order, view cart, payment information, order confirmation, etc.
If cookies are not stored then you need to perform login action every time before you execute the above listed test scenarios. This will increase your coding effort and execution time.
The solution is to store cookies in a file. Later on you can retrieve the values of cookie from this file and add it to your current browser session. As a result, you can skip the login steps in every test case because your driver session will have this information in it.
The application server now treats your browser session as authenticated one and directly takes you to your requested URL.
In Selenium Webdriver, we can query and interact with cookies with below given built-in method:
// Return The List of all Cookies
driver.manage().getCookies();
//Return specific cookie according to name
driver.manage().getCookieNamed(“<< Name of cookies>>”);
//Create and add the cookie
Cookie cookie = new Cookie(“uname”, “kiran”);
driver.manage().addCookie(cookie);
// Delete specific cookie
driver.manage().deleteCookie(cookie);
// Delete specific cookie according to name
driver.manage().deleteCookieNamed(“<< Name of cookies>>”);
// Delete all cookies
driver.manage().deleteAllCookies();
Try printing all cookies in our example from flipkart.com.
package com.javabykiran;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CookiesEx {
public static void main(String[] args) {
// opens a Firefox browser
WebDriver driver = new FirefoxDriver();
// opening of url
driver.get("https://www.flipkart.com");
// Maximize window
driver.manage().window().maximize();
Set< Cookie > cookies = driver.manage().getCookies();
for (Cookie cookie : cookies) {
System.out.println("========== Cookie Details ============");
System.out.println("name of cookie >> " + cookie.getName());
System.out.println("value for cookie >> " + cookie.getValue());
System.out.println("doamin name >>" + cookie.getDomain());
System.out.println("getExpiry" + cookie.getExpiry());
System.out.println("isSecure >> " + cookie.isSecure());
}
}
}
Whenever we try to access HTTPS website or application so many time you will face untrusted SSL certificate issue. This issue comes in all browser like IE,Chrome,Safari, Firefox etc.
Each secure site has Certificate so its certificate is not valid up-to-date.
Certificate has been expired on date.
Certificate is only valid for (site name).
The certificate is not trusted because the issuer certificate is unknown due to many reasons.
Step 1- We have to create FirefoxProfile in Selenium.
Step 2- We have some predefined method in Selenium called setAcceptUntrustedCertificates() which accept Boolean values (true/false)- so we will make it true.
Step 3- Open Firefox browser with the above-created profile.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class SSLCertificate {
public static void main(String[] args) {
//It create firefox profile
FirefoxProfile profile = new FirefoxProfile();
// This will set the true value
profile.setAcceptUntrustedCertificates(true);
// This will open firefox browser using above created profile
WebDriver driver = new FirefoxDriver(profile);
driver.get("pass the url as per your requirement");
}
}
// Create object of DesiredCapabilities class
DesiredCapabilities cap=DesiredCapabilities.chrome();
// Set ACCEPT_SSL_CERTS variable to true
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Set the driver path
System.setProperty("webdriver.chrome.driver","Chrome driver path");
// Open browser with capability
WebDriver driver=new ChromeDriver(cap);
// Create object of DesiredCapabilities class
DesiredCapabilitiescap = DesiredCapabilities.internetExplorer();
// Set ACCEPT_SSL_CERTS variable to true
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Set the driver path
System.setProperty("webdriver.ie.driver","IE driver path");
// Open browser with capability
WebDriver driver = newInternetExplorerDriver(cap);
There are many advantages by using FirefoxProfile preferences in selenium. You have to update the preferences within Firefox. We can do this by instantiating a Firefox Profile object and then update the settings.We will then need to pass this object into FirefoxDriver which will load the profile with your defined settings.
FirefoxProfile profile = new FirefoxProfile ();
profile.setPreference(“browser.startup.homepage”, ”http://www.javabykiran.com/);
WebDriver driver = new FirefoxDriver(profile);
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference( “intl.accept_languages”, “no,enus,en” );
WebDriver driver = new FirefoxDriver(profile);
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference(“general.useragentoverride”, “Any UserAgent String”);
WebDriver driver = new FirefoxDriver(profile);
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference(“browser.download.folderList”,2);
profile.setPreference(“browser.download.manager.showWhenStarting”, false);
profile.setPreference(“browser.download.dir”, downloadPath);
profile.setPreference(“browser.helperApps. neverAsk.openFile”,”application/excel”);
profile.setPreference(“browser.helperApps. neverAsk.saveToDisk”,”application/excel”);
profile.setPreference(“browser.helperApps.alwaysAsk. force”, false);
profile.setPreference(“browser.download.manager.showAlertOnComplete”, false);
profile.setPreference(“browser.download.manager.closeWhenDone”, false);
FirefoxProfile profile = allProfiles.getProfile(“CertificateIssue”);
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
WebDriver driver = new FirefoxDriver(profile);
driver.get(“http://www.javabykiran.com/”);
In web application we have to verify all the links whether they are broken means the after clicking on link ‘page not found’ page displays.
Below is the code:
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class VerifyLinks {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.google.co.in");
List< WebElement > allLink = driver.findElements(By.tagName("a"));
System.out.println("Total links are " + allLink.size());
for (int i = 0; i < allLink.size(); i++) {
WebElement ele = allLink.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) {
}
}
}
package com.jbk;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScrollPgeDown {
public static void main(String[] args) throws Exception {
// load browser
WebDriver driver=new FirefoxDriver();
// maximize browser
driver.manage().window().maximize();
// Open Application
driver.get("http://www.javabykiran.com/");
// Wait for 5 seconds
Thread.sleep(5000);
// This will scroll page 3000 pixel vertical
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("scrollBy(0,3000)");
}
}
package com.jbk;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WindowHandle {
public static void main(String[] args)
{
WebDriver driver = new FirefoxDriver();
driver.get("https://www.naukri.com/");
driver.manage().window().maximize();
String parent_window = driver.getWindowHandle();
Set< String > allwindow = driver.getWindowHandles();
Iterator< String > itr = allwindow.iterator();
while(itr.hasNext()) {
String child_window=itr.next();
if(!parent_window.equals(child_window)){
driver.switchTo().window(child_window);
System.out.println("child windows title is "+driver.getTitle());
driver.close();
}
}
driver.switchTo().window(parent_window);
}
}