Browser Commands of Selenium WebDriver in Java


Browser Commands of Selenium WebDriver
Selenium Webdriver need to open and close browser. Below are the numbers of commands you can apply on the Selenium opened browser.

Get Command
Method Name: get(String url)
Syntax: driver.get(String url);
Purpose: open new web page in the current browser.
Example:
driver.get("wwww.google.com");

Get Title Command
Method Name: getTitle()
Syntax: driver.getTitle();
Purpose: get the title of the current page.
Example:
driver.getTitle();

Get Current URL Command
Method Name: getCurrentUrl()
Syntax: driver.getCurrentUrl();
Purpose: get the URL of the page currently loaded in the browser.
Example:
driver.getCurrentUrl()

Get Page Source Command
Method Name: getPageSource();
Syntax: driver.getPageSource();
Purpose: get the source of the last loaded page.
Example:
driver.getPageSource();

Refresh Command
Method Name: refresh()
Syntax: driver.navigate().refresh();
Purpose: refresh the current browser.
Example:
driver.navigate().refresh();

Close Command
Method Name: close();
Syntax: driver.close();
Purpose: close the current window of the browser, if it’s the last window it will close the browser.
Example:

Quit Command
Method Name: quit()
Syntax: driver.quit();
Purpose: quit the browser and all the opened windows in the browser.
Example:
driver.quit();

Example
import java.util.concurrent.TimeUnit; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class BrowserCommands {
 
public static void main(String[] args) throws InterruptedException {
 
// Create a new instance of the Firefox driver 
WebDriver driver  driver = new FirefoxDriver();
 
//Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception 
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 
//Launch the Google Website 
driver.get("http://www.google.com");
 
// Storing Title name in String variable 
String sTitle = driver.getTitle();
 
// Storing Title length in Int variable 
int iTitleLength = driver.getTitle().length();
 
// Printing Title name on Console 
System.out.println(sTitle);
 
// Printing Title length on console 
System.out.println(iTitleLength);
 
// Storing URL in String variable 
sTitle = driver.getCurrentUrl();
 
// Storing URL length in Int variable 
iTitleLength = driver.getCurrentUrl().length();
 
// Printing URL on Console 
System.out.println(sTitle);
 
// Printing URL length on console 
System.out.println(iTitleLength);
 
// Refreshing current page 
driver.get(driver.getCurrentUrl());  
 
// Storing Page Source in String variable 
String sPageSource = driver.getPageSource();
 
// Storing Page Source length in Int variable 
int iPageSourceLength = driver.getPageSource().length();
 
// Printing Page Source on console 
System.out.println(sPageSource);
 
// Printing Page SOurce length on console 
System.out.println(iPageSourceLength);
 
//Closing browser 
driver.close();
 
 }
 
}

How to perform single and multiple selection from Dropdown in Selenium Webdriver using java.

HTML CODE:
<html>
<head>
<title>Selenium WebDriver- Drop Down Interaction</title>
</head>
<body>
<select multiple="multiple" id="language">
<option value="java">Java</option>
<option value="c">C</option>
<option value="perl">Perl</option>
<option value="php">PHP</option>
<option value="python">Python</option>
<option value="javascript">JavaScript</option>
</select>
</body>
</html>

Java code:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Singlemultiselection {

public static void main(String args[]) throws InterruptedException {
// Initialize Firefox Webdriver      
WebDriver driver = new FirefoxDriver();
//Resize current browser window on width and height
driver.manage().window().setSize(new Dimension(400, 400));
//Go to desire page      
driver.get("file:///C:/Users/Hiro%20Mia/Desktop/selection.html");
//Set  timeout      
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// select ByVisible Text
Select dropdown = new Select(driver.findElement(By.id("language")));
dropdown.selectByVisibleText("Java");
//Get the first selected option in this select tag 
System.out.println(dropdown.getFirstSelectedOption().getText());
Thread.sleep(4000);
// Deselect all options that display text matching the argument.
dropdown.deselectByVisibleText("Java");

//Select all options that have a value matching the argument
dropdown.selectByValue("php");
//Get the first selected option in this select tag 
System.out.println(dropdown.getFirstSelectedOption().getText());
Thread.sleep(4000);
dropdown.deselectByValue("php");

//Select the option at the given index.
dropdown.selectByIndex(4);
//Get the first selected option in this select tag 
System.out.println(dropdown.getFirstSelectedOption().getText());
Thread.sleep(4000);
// Deselect the option at the given index
dropdown.deselectByIndex(4);

// multiple selection
dropdown.selectByVisibleText("Java");
dropdown.selectByValue("php");
dropdown.selectByIndex(4);
// Return all selected options belonging to this select tag
System.out.println("==================");
List<WebElement> allselectedOptions = dropdown.getAllSelectedOptions();
for (WebElement webElement : allselectedOptions) {
    System.out.println(webElement.getText());
}
System.out.println("==================");
//Check multiple select
System.out.println(dropdown.isMultiple());
Thread.sleep(4000);

//Get all options belonging to this select tag 
System.out.println("==================");
List<WebElement> allOptions = dropdown.getOptions();
for (WebElement webElement : allOptions) {
    System.out.println(webElement.getText());
}

//close firefox browser  
driver.quit();
    }
}

How to operate browser Cookies in Selenium Webdriver using java.

cookie: An HTTP cookie (also called web cookie, Internet cookie, browser cookie or simply cookie, the latter which is not to be confused with the literal definition), is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website.
We can perform required task with respect to browser cookies in Selenium Webdriver and can add , delete, delete particular cookie by passing the name.

Add Cookie
Method Name: addCookie(Cookie cookie)
Syntax: driver.manage().addCookie(arg0);
Description: To add a specific cookie into cookies. If the cookie's domain name is left blank, it is assumed that the cookie is meant for the domain of the current document.
Example:
Cookie name = new Cookie("firefoxcookie", "123456789123");
driver.manage().addCookie(name);


Get the Cookie with Specific Name
Method Name: getCookieNamed(java.lang.String name)
Syntax: driver.manage().getCookieNamed(arg0);
Description: To Get a cookie with a given name.
Example:
driver.manage().getCookieNamed("firefoxcookie");

Get Cookies
Method Name: getCookies()
Syntax: driver.manage().getCookies();
Description: Get all the cookies for the current domain.
Example:
Set<Cookie> cookiesList1 = driver.manage().getCookies();
for (Cookie getcookies : cookiesList1) {
System.out.println(getcookies);
}


Delete Cookie with Name
Method Name: deleteCookieNamed(java.lang.String name)
Syntax: driver.manage().deleteCookieNamed(arg0);
Description: Delete the named cookie from the current domain.
Example:
driver.manage().deleteCookieNamed("firefoxcookie");

Delete All Cookies
Method Name: deleteAllCookies()
Syntax: driver.manage().deleteAllCookies();
Description: It will delete all the cookies for the current domain.
Example:
driver.manage().deleteAllCookies();

Full Example
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Handlecookie {

public static void main(String args[]) {
// Initialize Firefox Webdriver      
WebDriver driver = new FirefoxDriver();
//Maximize browser window       
driver.manage().window().maximize();
//Go to desire wbesite      
driver.get("http://www.google.com");
//Set  timeout      
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//pass name and value for cookie as parameters
Cookie name = new Cookie("firefoxcookie", "123456789123");
// Add Cookie
driver.manage().addCookie(name);

// Get the Cookie with Specific Name     
System.out.println(driver.manage().getCookieNamed("firefoxcookie"));


System.out.println("=======================================");
//Get all Cookies
Set<Cookie> cookiesList1 = driver.manage().getCookies();
for (Cookie getcookies : cookiesList1) {
    System.out.println(getcookies);
}
System.out.println("=======================================");


// Delete Cookie with Name    
driver.manage().deleteCookieNamed("firefoxcookie");

System.out.println("=======================================");
//Check deleted or not firefoxcookie Cookie 
Set<Cookie> cookiesList2 = driver.manage().getCookies();
for (Cookie getcookies : cookiesList2) {
    if (getcookies.getName().equals("firefoxcookie")) {
System.out.println(driver.manage().getCookieNamed("firefoxcookie"));
    } else {
System.out.println("There is no cookies name firefoxcookie");
break;
    }

}

System.out.println("=======================================");



//Delete all the cookies of the domain
driver.manage().deleteAllCookies();

// Check all the cookies deleted or not
Set<Cookie> cookiesList3 = driver.manage().getCookies();
if (cookiesList3.size() == 0) {
    System.out.println("There are no cookies");
}

//close firefox browser  
driver.quit();
    }
}


How to download pdf file from website in Selenium Webdriver using java.


 import java.io.BufferedInputStream;  
 import java.io.BufferedOutputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.OutputStream;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.util.ArrayList;  
 import java.util.List;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.htmlunit.HtmlUnitDriver;  
   
   
 public class pdffiledownloadfromwebsite {  
   
 public static void main(String[] args) throws MalformedURLException, IOException {  
  List&lt;String&gt; uniqurl = new ArrayList();  
   
 // Initialize Webdriver driver   
 WebDriver driver = new HtmlUnitDriver();  
 // Go to pdf page  
 driver.get("http://www.banglakitab.com/kitab.htm");  
 // get all page urls  
 List&lt;WebElement&gt; pdfurllist = driver.findElements(By.tagName("a"));  
   
 for (WebElement elemnet : pdfurllist) {  
 String pdfurl = elemnet.getAttribute("href").trim();  
 //check pdf url  
 if (pdfurl.contains(".pdf")) {  
 // check one file download one time  
 if (!(uniqurl.contains(pdfurl))) {  
  uniqurl.add(pdfurl);  
 //print file name and download url  
 System.out.println(filename(pdfurl) + " ---&gt; " + pdfurl);  
 //download file  
 URL url = new URL(pdfurl);  
 InputStream in = new BufferedInputStream(url.openStream());  
 OutputStream out = new BufferedOutputStream(new FileOutputStream(filename(pdfurl)));  
   
 for (int i; (i = in.read()) != -1;) {  
 out.write(i);  
 }  
 in.close();  
 out.close();  
             
  }  
  }  
 }  
   
 // close driver   
 driver.quit();  
   
 }  
   
   // get file name. It depend on download url pattent.  
   private static String filename(String url) {  
     String filename = "";  
     String file[];  
   
     file = url.split("\\/");  
     if (file[file.length - 1].contains("-")) {  
       filename = file[file.length - 1].trim().replace("-", " ");  
     } else if (file[file.length - 1].contains("%20")) {  
       filename = file[file.length - 1].trim().replace("%20", " ");  
     } else {  
       filename = file[file.length - 1].trim();  
     }  
   
     return filename;  
   }  
   
 }