0% found this document useful (0 votes)
129 views

S Det Selenium Imp File

The document contains code snippets from various Java Selenium projects. It includes the pom.xml file which defines the Selenium dependencies, test classes for login tests on OrangeHRM and demo tests using different locator strategies like ID, CSS and XPath. It also has examples to demonstrate XPath axes like self, parent etc.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views

S Det Selenium Imp File

The document contains code snippets from various Java Selenium projects. It includes the pom.xml file which defines the Selenium dependencies, test classes for login tests on OrangeHRM and demo tests using different locator strategies like ID, CSS and XPath. It also has examples to demonstrate XPath axes like self, parent etc.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

1.pom.

xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-


instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>seleniumproject</groupId>

<artifactId>seleniumproject</artifactId>

<version>0.0.1-SNAPSHOT</version>

<dependencies>

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->

<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>4.4.0</version>

</dependency>

<!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->

<dependency>

<groupId>io.github.bonigarcia</groupId>

<artifactId>webdrivermanager</artifactId>

<version>5.3.0</version>

</dependency>

</dependencies>

</project>

2.OrangeHRMLoginTest

package day17;

import org.openqa.selenium.By;

import org.openqa.selenium.NoSuchElementException;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;
/*

1) Launch browser

2) open url https://opensource-demo.orangehrmlive.com/

3) Provide username - Admin

4) Provide password - admin123

5) Click on Login button

6) Verify the title of dashboard page

Exp title : OrangeHRM

7) close browser

*/

import org.openqa.selenium.chrome.ChromeDriver;

public class OrangeHRMLoginTest {

public static void main(String[] args) throws InterruptedException {

//System.setProperty("webdriver.chrome.driver","C:\\Drivers\\chromedriver_win32\\chromedri
ver.exe");

//WebDriverManager.chromedriver().setup();

//1) Launch browser

//ChromeDriver driver=new ChromeDriver();

WebDriver driver=new ChromeDriver();

//2) open url on the browser

driver.get("https://opensource-demo.orangehrmlive.com/");

driver.manage().window().maximize(); // maximize the page

Thread.sleep(5000);
//3) Provide username - Admin

//WebElement txtUsername=driver.findElement(By.name("username"));

//txtUsername.sendKeys("Admin");

driver.findElement(By.name("username")).sendKeys("Admin");

//4) Provide password - admin123

driver.findElement(By.name("password")).sendKeys("admin");

//5) Click on Submit button

driver.findElement(By.xpath("//*[@id=\"app\"]/div[1]/div/div[1]/div/div[2]/div[2]/form/div[3]/b
utton")).click();

Thread.sleep(7000);

//6) Verify the title of dashboard page

//Title validation

/*String act_title=driver.getTitle();

String exp_title="OrangeHRM";

if(act_title.equals(exp_title))

System.out.println("Test passed");

else

System.out.println("failed");

*/

// Lable validation after successful login

String act_label = "";

try
{

act_label=driver.findElement(By.xpath("//*[@id='app']/div[1]/div[1]/header/div[1]/div[1]/span/h
6")).getText();

catch(NoSuchElementException e) {

String exp_label="Dashboard";

if(act_label.equals(exp_label))

System.out.println("test passed");

else

System.out.println("test failed");

//7) close browser

//driver.close();

driver.quit();

3.LocatorsDemo1

package day18;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class LocatorsDemo1 {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

//Open app

driver.get("http://automationpractice.com/index.php");

driver.manage().window().maximize(); // maximize browser window

//search box

driver.findElement(By.id("search_query_top")).sendKeys("T-shirts");

//search button

driver.findElement(By.name("submit_search")).click();

//link text & partial linktext

//driver.findElement(By.linkText("Printed Chiffon Dress")).click();

driver.findElement(By.partialLinkText("Printed Chiffon")).click()}}

4.LocatorsDemo2

package day18;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class LocatorsDemo2 {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

//Open app

driver.get("http://automationpractice.com/index.php");

driver.manage().window().maximize(); // maximize browser window

//Finding number of sliders on home page

List<WebElement> sliders=driver.findElements(By.className("homeslider-container"));

System.out.println("Number of sliders:"+sliders.size());

//Find Total number of images in home page

List<WebElement> images=driver.findElements(By.tagName("img"));

System.out.println("Total number of images:"+images.size());

//Find total number of links

List<WebElement> links=driver.findElements(By.tagName("a"));

System.out.println("Total number of links:"+ links.size());

driver.quit();
}

5.CssSelectorsDemo

package day19;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class CSSSelectorsDemo {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://demo.nopcommerce.com/");

driver.manage().window().maximize();

//css with tag & id

//driver.findElement(By.cssSelector("input#small-searchterms")).sendKeys("MacBook");

//driver.findElement(By.cssSelector("#small-searchterms")).sendKeys("MacBook");
//tag class

//driver.findElement(By.cssSelector("input.search-box-text")).sendKeys("MacBook");

//driver.findElement(By.cssSelector(".search-box-text")).sendKeys("MacBook");

//tag & attribute

//driver.findElement(By.cssSelector("input[name='q']")).sendKeys("MacBook");

//driver.findElement(By.cssSelector("[name='q']")).sendKeys("MacBook");

//tag class & attribute

driver.findElement(By.cssSelector("input.search-box-
text[name='q']")).sendKeys("MacBook");

}}

6.XpathDemo

package day20;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class XPathDemo {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();
WebDriver driver=new ChromeDriver();

driver.get("https://demo.opencart.com/");

driver.manage().window().maximize();

String productname= driver.findElement(By.xpath("//a[normalize-


space()='MacBook']")).getText();

//String
productname=driver.findElement(By.xpath("/html[1]/body[1]/main[1]/div[2]/div[1]/div[1]/div[2]/div
[1]/form[1]/div[1]/div[2]/div[1]/h4[1]/a[1]")).getText();

System.out.println(productname);

7.XpathAxes

package day21;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
public class XPathAxes {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://money.rediff.com/gainers/bse/daily/groupa");

driver.manage().window().maximize();

//Self - Selects the current node

String text=driver.findElement(By.xpath("//a[contains(text(),'NIIT
Ltd')]/self::a")).getText();

System.out.println("Self : "+ text); //NIIT Ltd

//Parent - Selects the parent of the current node (always One)

text=driver.findElement(By.xpath("//a[contains(text(),'NIIT
Ltd')]/parent::td")).getText();// there is no text for parent, so it is same value display

System.out.println("Parent : "+text); //NIIT Ltd

//Child - Selects all children of the current node (One or many)

List<WebElement> childs=driver.findElements(By.xpath("//a[contains(text(),'NIIT
Ltd')]/ancestor::tr/child::td"));

System.out.println("Number of child elements:"+childs.size());//5

//Ancestor - Selects all ancestors (parent, grandparent, etc.)

text=driver.findElement(By.xpath("//a[contains(text(),'NIIT Ltd')]/ancestor::tr")).getText();

System.out.println("Ancestor : "+text);

//Descendant - Selects all descendants (children, grandchildren, etc.) of the current node

List<WebElement> descendants=driver.findElements(By.xpath("//a[contains(text(),'NIIT
Ltd')]/ancestor::tr/descendant::*"));
System.out.println("Number of descendant nodes:"+descendants.size());

//Following -Selects everything in the document after the closing tag of the current node

List<WebElement>followingnodes=driver.findElements(By.xpath("//a[contains(text(),'NIIT
Ltd')]/ancestor::tr/following::tr"));

System.out.println("Number of following nodes:"+followingnodes.size());

//Following-sibling : Selects all siblings after the current node

List<WebElement>
followingsiblings=driver.findElements(By.xpath("//a[contains(text(),'NIIT Ltd')]/ancestor::tr/following-
sibling::tr"));

System.out.println("Number of Following Siblings:"+followingsiblings.size());

//Preceding - Selects all nodes that appear before the current node in the document

List<WebElement> precedings=driver.findElements(By.xpath("//a[contains(text(),'NIIT
Ltd')]/ancestor::tr/preceding::tr"));

System.out.println("Number of preceding nodes:"+precedings.size());

//preceding-sibling - Selects all siblings before the current node

List<WebElement>
precedingsiblings=driver.findElements(By.xpath("//a[contains(text(),'NIIT Ltd')]/ancestor::tr/preceding-
sibling::tr"));

System.out.println("Number of preceding sibling nodes:"+precedingsiblings.size());

driver.quit(); } }

8.GetMethods

package day22;

import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

/*get(url)

getTitle()

getCurrentURL()

getPageSource()

getWindowHandle()

getwindowHandles()

*/

public class GetMethods {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

driver.manage().window().maximize();

System.out.println("title of the page:"+driver.getTitle());

System.out.println("Current URL:"+ driver.getCurrentUrl());

/*System.out.println("Page source......................");

String ps=driver.getPageSource();

System.out.println(ps);

System.out.println(ps.contains("html"));*/
//System.out.println(driver.getWindowHandle()); //CDwindow-
3127F2DCB717E0F5993100E70756C523

//CDwindow-46E50E8AE6529C7635BCF8E9EA2FB5DE

Thread.sleep(3000);

driver.findElement(By.linkText("OrangeHRM, Inc")).click(); // opens new browser window

Set<String> windowids=driver.getWindowHandles();

for(String winid:windowids)

System.out.println(winid); //CDwindow-
B9429C1F5CC606A3981FAF0CD1A96DBC

//CDwindow-
339CE5C5C5FB731B207639DE22EC40D1

9.BrowserCommands

package day22;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class BrowserCommands {


public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://opensource-demo.orangehrmlive.com/");

driver.manage().window().maximize();

Thread.sleep(3000);

driver.findElement(By.linkText("OrangeHRM, Inc")).click();

Thread.sleep(5000);

//driver.close(); // single browser window

driver.quit(); // all browser windows

10.ConditionalCommands

package day22;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
public class ConditionalCommands {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://demo.nopcommerce.com/register");

driver.manage().window().maximize();

// isDisplayed() isEnabled()

//WebElement logo=driver.findElement(By.xpath("//img[@alt='nopCommerce demo


store']"));

//System.out.println("displsy status of logo:"+logo.isDisplayed());

//boolean status=driver.findElement(By.xpath("//img[@alt='nopCommerce demo


store']")).isDisplayed();

//System.out.println(status);

//WebElement searchbox=driver.findElement(By.xpath("//input[@id='small-
searchterms']"));

//System.out.println("Dispay status:"+searchbox.isDisplayed());

//System.out.println("Enable status:"+searchbox.isEnabled());

//isSelected()

WebElement male_rd=driver.findElement(By.xpath("//input[@id='gender-male']"));

WebElement female_rd=driver.findElement(By.xpath("//input[@id='gender-female']"));

//Before selection

System.out.println("Before selection...............");

System.out.println(male_rd.isSelected()); //false
System.out.println(female_rd.isSelected()); //false

//After selection of male radio button

System.out.println("After selection of male radiop button............");

male_rd.click();

System.out.println(male_rd.isSelected()); //true

System.out.println(female_rd.isSelected()); //false

//After selection of fe-male radio button

System.out.println("After selection of female radiop button............");

female_rd.click();

System.out.println(male_rd.isSelected()); //false

System.out.println(female_rd.isSelected()); //true

11.NavigationalCommands

package day23;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class NavigationalCommands {

public static void main(String[] args) {


WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.navigate().to("https://www.amazon.in/");

System.out.println(driver.getCurrentUrl());

driver.navigate().to("https://www.flipkart.com/");

System.out.println(driver.getCurrentUrl());

driver.navigate().back();

System.out.println(driver.getCurrentUrl()); // amzon

driver.navigate().forward();

System.out.println(driver.getCurrentUrl()); // flipkart

driver.navigate().refresh(); // refresh the page

12.SleepStatement

package day23;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
public class SleepStatement {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

Thread.sleep(5000);

driver.findElement(By.xpath("//input[@placeholder='Username']")).sendKeys("Admin");

13.ImplicitWait

package day23;

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class ImplicitWait {


public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // implicit command

driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

driver.findElement(By.xpath("//input[@placeholder='Username']")).sendKeys("Admin");

driver.findElement(By.xpath("//input[@placeholder='Password']")).sendKeys("admin123");

14.ExplicitWait
package day23;

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

import io.github.bonigarcia.wdm.WebDriverManager;

public class ExplicitWaitDemo {


public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

//declaring explicit wait

WebDriverWait mywait=new WebDriverWait(driver,Duration.ofSeconds(10));

driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

WebElement
username=mywait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@placeholder=
'Username']")));

useranme.sendKeys("Admin");

WebElement
password=mywait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@placeholder='
Password']")));

password.sendKeys("admin123");

}}

15.FluentWaitDemo

package day23;

import java.time.Duration;

import java.util.NoSuchElementException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.FluentWait;

import org.openqa.selenium.support.ui.Wait;

import com.google.common.base.Function;

import io.github.bonigarcia.wdm.WebDriverManager;

public class FluentWaitDemo {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

//Fluent wait declaration

FluentWait mywait=new FluentWait(driver);

mywait.withTimeout(Duration.ofSeconds(30));

mywait.pollingEvery(Duration.ofSeconds(5));

mywait.ignoring(NoSuchElementException.class);

//usage

WebElement username=(WebElement)
mywait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@placeholder='Username'
]")));
username.sendKeys("Admin");

16.Handling Checkboxes

package day24;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class HandleCheckboxes {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://itera-qa.azurewebsites.net/home/automation");
driver.manage().window().maximize();

//select specific one checkbox

//driver.findElement(By.xpath("//input[@id='monday']")).click();

//total number of checkboxes

List<WebElement> checkboxes=driver.findElements(By.xpath("//input[@class='form-
check-input' and @type='checkbox']"));

System.out.println("Total number of checkboxes:"+checkboxes.size()); //7

//Select all the checkboxes

/*for(int i=0;i<checkboxes.size();i++)

checkboxes.get(i).click();

}*/

/*for(WebElement chkbox:checkboxes)

chkbox.click();

}*/

//Select last 2 checkboxes

// total Number of checkboxes-how many checkboxes to be selected= startign index

//7-3= 4 ( startign index)

/*for(int i=4;i<checkboxes.size();i++)

checkboxes.get(i).click();

}*/

//Select first 2 chekboxes

/*for(int i=0;i<3;i++)
{

checkboxes.get(i).click();

}*/

/*for(int i=0;i<checkboxes.size();i++)

if(i<2)

checkboxes.get(i).click();

}*/

//clear/Uncheck checkboxes

//Using normal for loop

for(int i=0;i<3;i++)

checkboxes.get(i).click();

Thread.sleep(4000);

/*for(int i=0;i<checkboxes.size();i++)

if(checkboxes.get(i).isSelected())

checkboxes.get(i).click();

}*/

for(WebElement chkbox:checkboxes)

{
if(chkbox.isSelected())

chkbox.click();

17.Handle Dropdown With select tag

package day24;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.Select;

import io.github.bonigarcia.wdm.WebDriverManager;

import io.opentelemetry.exporter.logging.SystemOutLogExporter;

public class HandleDropDownwithSelectTag {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();


driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://phppot.com/demo/jquery-dependent-dropdown-list-countries-and-
states/");

driver.manage().window().maximize();

WebElement drpCountryEle=driver.findElement(By.xpath("//select[@id='country-list']"));

Select drpCountry=new Select(drpCountryEle);

//1) Selecting an option from teh dropdown

//drpCountry.selectByVisibleText("USA");

//drpCountry.selectByValue("4"); // use this only if value attribute is present for option


tag

//drpCountry.selectByIndex(3); //France

// 2) Find total options in dropdown

List<WebElement> options=drpCountry.getOptions();

System.out.println("total number of options:"+options.size());

//3) print options in console window

/*for(int i=0;i<options.size();i++)

System.out.println(options.get(i).getText());

}*/

//using enhanced loop

for(WebElement op:options)

System.out.println(op.getText());

}
}

18.Handle Dropdown Without Select tag

package day24;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class HandleDropDownWithoutSelectTag {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://www.jquery-az.com/boots/demo.php?ex=63.0_2");

driver.manage().window().maximize();
//clicking on the dropdown

driver.findElement(By.xpath("//button[contains(@class,'multiselect')]")).click();

List<WebElement>
options=driver.findElements(By.xpath("//ul[contains(@class,multiselect)]//label"));

//find total number of options

System.out.println("Total number of options:"+options.size());

//print all the options from dropdown

//using normal for loop

/*for(int i=0;i<options.size();i++)

System.out.println(options.get(i).getText());

}*/

//select options from dropdown

/*for(int i=0;i<options.size();i++)

String option=options.get(i).getText();

if(option.equals("Java") || option.equals("Python"))

options.get(i).click();

}*/

for(WebElement option:options)

{
String text=option.getText();

if(text.equals("Java") || text.equals("Python"))

option.click();

19.Auto Suggest Dropdown

package day25;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class AutoSuggestDropDown {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://www.google.com/");

driver.manage().window().maximize();

driver.findElement(By.xpath("//input[@name='q']")).sendKeys("selenium");

Thread.sleep(3000);

List<WebElement>
list=driver.findElements(By.xpath("//div[contains(@class,'wM6W7d')]//span"));

System.out.println("Number of suggestions:"+list.size());

//select an option from list

for(int i=0;i<list.size();i++)

String text=list.get(i).getText();
if(text.equals("selenium tutorial"))

list.get(i).click();

break;

}}

20.Handle Alerts

package day25;

import java.time.Duration;

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

import io.github.bonigarcia.wdm.WebDriverManager;

public class HandleAlerts {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();


WebDriverWait mywait=new WebDriverWait(driver,Duration.ofSeconds(10));

driver.get("https://the-internet.herokuapp.com/javascript_alerts");

driver.manage().window().maximize();

driver.findElement(By.xpath("//button[text()='Click for JS Confirm']")).click();

//Alert alertwindow=driver.switchTo().alert();

Alert alertwindow=mywait.until(ExpectedConditions.alertIsPresent());

System.out.println(alertwindow.getText());

//alertwindow.accept(); // this will close alert window using ok button

alertwindow.dismiss(); // close alert window by using cancel button

21.Alert with Input Box

package day25;

import java.time.Duration;

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

import io.github.bonigarcia.wdm.WebDriverManager;

public class AlertwithInputbox {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://the-internet.herokuapp.com/javascript_alerts");

driver.manage().window().maximize();

driver.findElement(By.xpath("//button[normalize-space()='Click for JS Prompt']")).click();

Alert alertwindow=driver.switchTo().alert();

System.out.println(alertwindow.getText());

alertwindow.sendKeys("welcome");

alertwindow.accept();

//alertwindow.dismiss();

//validation

String act_text=driver.findElement(By.xpath("//p[@id='result']")).getText();

String exp_text="You entered: welcome";


System.out.println(act_text);

System.out.println(exp_text);

if(act_text.equals(exp_text))

System.out.println("test passed");

else

System.out.println("test failed");

22.Authenticated Popup

package day25;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class AuthenticatedPopop {


public static void main(String[] args)

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

//http://the-internet.herokuapp.com/basic_auth

//http://admin:[email protected]/basic_auth

driver.get("http://admin:[email protected]/basic_auth");

String text=driver.findElement(By.xpath("//p[contains(text(),'Congratulations!')]")).getText();

if(text.contains("Congratulations"))

System.out.println("successful login");

else

System.out.println("login failed");

23.Handle Browser Windows

package day26;

import java.time.Duration;
import java.util.ArrayList;

import java.util.List;

import java.util.Set;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class HandleBrowserWindows {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

driver.manage().window().maximize();

driver.findElement(By.xpath("//a[normalize-space()='OrangeHRM, Inc']")).click();

//capture id's for browser windows

Set<String> windowIDs=driver.getWindowHandles(); // store 2 window id's

//Approach1 - using List collection

/*

List <String>windowidsList=new ArrayList(windowIDs); // converted Set ---> List

String parentWindowID=windowidsList.get(0);
String childWindowID=windowidsList.get(1);

//Swith to child window

driver.switchTo().window(childWindowID);

driver.findElement(By.xpath("//div[@class='d-flex web-menu-btn']//li[1]//a[1]")).click();

//Switch to parent window

driver.switchTo().window(parentWindowID);

driver.findElement(By.xpath("//input[@placeholder='Username']")).sendKeys("admin");

*/

//Appraoch2

/*for(String winid:windowIDs)

String title=driver.switchTo().window(winid).getTitle();

if( title.equals("OrangeHRM HR Software | Free & Open Source HR Software |


HRMS | HRIS | OrangeHRM"))

driver.findElement(By.xpath("//div[@class='d-flex web-menu-
btn']//li[1]//a[1]")).click();

}*/

//closing specific browser windows based on choice

// 1-x 2-y 3-z 4-a 5-b...........

/*for(String winid:windowIDs)

String title=driver.switchTo().window(winid).getTitle();
if( title.equals("x") || title.equals("y") || title.equals("z"))

driver.close();

}*/

for(String winid:windowIDs)

String title=driver.switchTo().window(winid).getTitle();

if( title.equals("OrangeHRM HR Software | Free & Open Source HR Software |


HRMS | HRIS | OrangeHRM"))

driver.close();

24.Handle Frames Demo

package day26;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class HandleFramesDemo1 {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://www.selenium.dev/selenium/docs/api/java/index.html?overview-
summary.html");

driver.manage().window().maximize();

driver.switchTo().frame("packageListFrame");

driver.findElement(By.linkText("org.openqa.selenium")).click();// frame1

driver.switchTo().defaultContent();// switch back to page

driver.switchTo().frame("packageFrame");

driver.findElement(By.linkText("WebDriver")).click(); // frame2

driver.switchTo().defaultContent();// switch back to page

driver.switchTo().frame("classFrame");

driver.findElement(By.xpath("//div[@class='topNav']//a[normalize-
space()='Overview']")).click();

}
25.Handle Inner Frames Demo

package day26;

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class HandleInnerFramesDemo {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://ui.vision/demo/webtest/frames/");

driver.manage().window().maximize();

//Frame1

WebElement frm1=driver.findElement(By.xpath("//frame[@src='frame_1.html']"));

driver.switchTo().frame(frm1);

driver.findElement(By.xpath("//input[@name='mytext1']")).sendKeys("11111");

driver.switchTo().defaultContent();
//Frame3

WebElement frm3=driver.findElement(By.xpath("//frame[@src='frame_3.html']"));

driver.switchTo().frame(frm3);

driver.findElement(By.xpath("//input[@name='mytext3']")).sendKeys("33333");

//inner frame

driver.switchTo().frame(0);

driver.findElement(By.cssSelector("div.AB7Lab")).click(); // select first radio button in


frame

driver.switchTo().defaultContent();

26.Handling Static Table

package day27;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class StaticTableDemo {

public static void main(String[] args) {


WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://testautomationpractice.blogspot.com/");

driver.manage().window().maximize();

// 1) Find total number of rows

int rows=driver.findElements(By.xpath("//table[@name='BookTable']//tr")).size(); //7


preferred

//int rows=driver.findElements(By.tagName("tr")).size(); //8 prefered only if you have


one single table

System.out.println("Number of rows:"+ rows); //7

//2) Find total number of columns

int cols=driver.findElements(By.xpath("//table[@name='BookTable']//th")).size();

//int cols=driver.findElements(By.tagName("th")).size(); // dont prefer if you have


multiple tables

System.out.println("Number of columns:"+ cols); //4

//3) Read specific row & column data

//String
value=driver.findElement(By.xpath("//table[@name='BookTable']//tr[7]//td[1]")).getText();

//System.out.println(value); //Master In JS
//4) Read data from all the rows & columns

/*System.out.println("Book Name"+" "+"Author"+" "+"Subject"+" "+"Price");

for(int r=2;r<=rows;r++)

for(int c=1;c<=cols;c++)

String
value=driver.findElement(By.xpath("//table[@name='BookTable']//tr["+r+"]//td["+c+"]")).getText();

System.out.print(value+"\t");

System.out.println();

*/

//5) Print book names whose author is Amit

/*for(int r=2;r<=rows;r++)

String
author=driver.findElement(By.xpath("//table[@name='BookTable']//tr["+r+"]/td[2]")).getText();

if(author.equals("Mukesh"))

String
bookname=driver.findElement(By.xpath("//table[@name='BookTable']//tr["+r+"]/td[1]")).getText();

System.out.println(author+" "+bookname);

}
}*/

//6)Find sum of prices for all the books

int sum=0;

for(int r=2;r<=rows;r++)

String
price=driver.findElement(By.xpath("//table[@name='BookTable']//tr["+r+"]/td[4]")).getText();

sum=sum+Integer.parseInt(price);

System.out.println("Total price of books:"+sum);

27.Handling Pagination Table

package day27;

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
public class PaginationTable {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://demo.opencart.com/admin/index.php");

driver.manage().window().maximize();

//Login

WebElement username=driver.findElement(By.id("input-username"));

username.clear();

username.sendKeys("demo"); //demo

WebElement password=driver.findElement(By.id("input-password"));

password.clear();

password.sendKeys("demo"); //demo

driver.findElement(By.xpath("//button[text()=' Login']")).click();

if(driver.findElement(By.xpath("//button[@class='btn-close']")).isDisplayed())

driver.findElement(By.xpath("//button[@class='btn-close']")).click();

//Customers--->customers
driver.findElement(By.xpath("//a[@class='parent collapsed'][normalize-
space()='Customers']")).click();

driver.findElement(By.xpath("//ul[@class='collapse
show']//a[contains(text(),'Customers')]")).click();

String text=driver.findElement(By.xpath("//div[@class='col-sm-6 text-end']")).getText();


//Showing 91 to 100 of 5513 (552 Pages)

int total_pages=Integer.parseInt(text.substring(text.indexOf("(")+1,text.indexOf("Pages")-
1));

System.out.println("Total number of pages:"+total_pages);

for(int p=1;p<=10;p++) //for(int p=1;p<=total_pages;p++)

if(total_pages>1)

WebElement
active_Page=driver.findElement(By.xpath("//ul[@class='pagination']//li//*[text()="+p+"]"));

System.out.println(" Active Page : "+active_Page.getText());

active_Page.click();

Thread.sleep(2000);

int noOfrows=driver.findElements(By.xpath("//table[@class='table table-


bordered table-hover']//tbody//tr")).size();

System.out.println(" Total No Of Rows in active Page : "+noOfrows);

for(int r=1;r<=noOfrows;r++)

{
String
customerName=driver.findElement(By.xpath("//table[@class='table table-bordered table-
hover']//tbody//tr["+r+"]//td[2]")).getText();

String
customerEmail=driver.findElement(By.xpath("//table[@class='table table-bordered table-
hover']//tbody//tr["+r+"]//td[3]")).getText();

String status=driver.findElement(By.xpath("//table[@class='table table-


bordered table-hover']//tbody//tr["+r+"]//td[5]")).getText();

System.out.println(customerName+" "+customerEmail+"
"+status);

driver.quit();

28.DropDown with the Hidden Options

package day28;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
public class DropDownWithHiddenOptions {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://opensource-demo.orangehrmlive.com/");

driver.manage().window().maximize();

driver.findElement(By.name("username")).sendKeys("Admin");

driver.findElement(By.name("password")).sendKeys("admin123");

driver.findElement(By.xpath("//button[normalize-space()='Login']")).click();

//Dropwdown

driver.findElement(By.xpath("//div[6]//div[1]//div[2]//div[1]//div[1]//div[2]")).click();//
opens the dropdown

List<WebElement>
options=driver.findElements(By.xpath("//div[@role='listbox']//span"));

for(WebElement option:options)

//System.out.println(option.getText());

if(option.getText().equals("Finance Manager"))
{

option.click();

break;

}} }

29.Find the smaller number in an array

package day28;

import java.util.Arrays;

public class FindSmallerNumberinArray {

public static void main(String[] args) {

//removing dollor sign

String price="$200.98";

String price1=price.replace("$",""); // remove the dollor sign

System.out.println(Double.parseDouble(price1)); //converted to number

//find smallest number in array

int a[]= {500,400,100,200,700};

Arrays.sort(a);

System.out.println("smallest number:"+a[0]);

System.out.println("$"+a[0]);
}

30.Date Picker Demo

package day28;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class DatePickerDemo {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://jqueryui.com/datepicker/");

driver.manage().window().maximize();

driver.switchTo().frame(0); //switth to frame

//Appraoch 1

//driver.findElement(By.xpath("//input[@id='datepicker']")).sendKeys("10/15/2022"); //
mm/dd/yyyy

//Approach2

String year="2024";

String month="October";

String date="12";

driver.findElement(By.xpath("//input[@id='datepicker']")).click(); // will open the date


picker

//select month & year

while(true)

String mon=driver.findElement(By.xpath("//span[@class='ui-datepicker-
month']")).getText();

String yr=driver.findElement(By.xpath("//span[@class='ui-datepicker-
year']")).getText();

if(mon.equals(month) && yr.equals(year))

break;

}
//driver.findElement(By.xpath("//span[@class='ui-icon ui-icon-circle-triangle-
e']")).click(); // Future date

//driver.findElement(By.xpath("//span[@class='ui-icon ui-icon-circle-triangle-
w']")).click(); //Past date

//select date

List<WebElement> allDates=driver.findElements(By.xpath("//table[@class='ui-
datepicker-calendar']//td"));

for(WebElement dt:allDates)

if(dt.getText().equals(date))

dt.click();

break;

/*for(int i=0;i<allDates.size();i++)

if(allDates.get(i).getText().equals(date))

allDates.get(i).click();

break;

}*/
}

31. Mouse Hover Demo

package day29;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class MouseHoverDemo {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver =new ChromeDriver();

driver.get("https://demo.opencart.com/");

driver.manage().window().maximize();

WebElement desktops=driver.findElement(By.xpath("//a[normalize-
space()='Desktops']"));
WebElement mac=driver.findElement(By.xpath("//a[normalize-space()='Mac (1)']"));

Actions act=new Actions(driver);

//Mouse hover

//act.moveToElement(desktops).moveToElement(mac).click().build().perform();//
creating action then perform

act.moveToElement(desktops).moveToElement(mac).click().perform(); // directly
performing action

32. Location of an Element

package day29;

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.Point;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
public class LocationOfElement {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

WebElement logo=driver.findElement(By.xpath("//img[@alt='company-branding']"));

System.out.println("Before maximizing window:"+logo.getLocation()); //(250, 202)

driver.manage().window().maximize();

System.out.println("After maximizing window:"+logo.getLocation()); //(660, 185)

driver.manage().window().minimize();

System.out.println("After minimizing window:"+logo.getLocation()); //(250, 157)

driver.manage().window().fullscreen();

System.out.println("After Full screen window:"+logo.getLocation()); //(660, 233)

Point p=new Point(100,100);

driver.manage().window().setPosition(p);

System.out.println("After setting window 100 * 100:"+logo.getLocation()); //(251, 159)

p=new Point(50,50);

driver.manage().window().setPosition(p);
System.out.println("After setting window 50 * 50:"+logo.getLocation()); //(252, 160)

33. Right Click Demo

package day29;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class RightClickDemo {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver =new ChromeDriver();

driver.get("http://swisnl.github.io/jQuery-contextMenu/demo.html");

driver.manage().window().maximize();

WebElement button=driver.findElement(By.xpath("//span[@class='context-menu-one
btn btn-neutral']"));
Actions act=new Actions(driver);

//right click

act.contextClick(button).perform();

driver.findElement(By.xpath("//span[normalize-space()='Copy']")).click(); // click on copy


option

Thread.sleep(5000);

driver.switchTo().alert().accept(); // close alert window

34. Slider Demo

package day29;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import io.github.bonigarcia.wdm.WebDriverManager;
public class SliderDemo {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.get("https://www.jqueryscript.net/demo/Price-Range-Slider-jQuery-UI/");

driver.manage().window().maximize();

Actions act=new Actions(driver);

//Min slider

WebElement min_slider=driver.findElement(By.xpath("//span[1]"));

System.out.println("Current location of min slider:"+min_slider.getLocation()); //(59,


250) x,y

act.dragAndDropBy(min_slider, 100, 250).perform();

System.out.println("Location of min slider After moving:"+min_slider.getLocation());

//Max slider

WebElement max_slider=driver.findElement(By.xpath("//span[2]"));

System.out.println("Current location of max slider:"+max_slider.getLocation()); //(796,


250)

act.dragAndDropBy(max_slider, -96, 250).perform();

System.out.println("Location of max slider after moving:"+max_slider.getLocation());

}
35. Drag and Drop Demo

package day29;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class DragAndDropDemo {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver =new ChromeDriver();

driver.get("http://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-
3.html");

driver.manage().window().maximize();
Actions act=new Actions(driver);

// rome---> Italy

WebElement rome=driver.findElement(By.xpath("//div[@id='box6']"));

WebElement italy=driver.findElement(By.xpath("//div[@id='box106']"));

act.dragAndDrop(rome, italy).perform(); // drag and drop

// Wasington---> USA

WebElement washington=driver.findElement(By.xpath("//div[@id='box3']"));

WebElement usa=driver.findElement(By.xpath("//div[@id='box103']"));

act.dragAndDrop(washington, usa).perform();

36. Double Click Demo

package day29;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import io.github.bonigarcia.wdm.WebDriverManager;
public class DoubleClickDemo {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver =new ChromeDriver();

driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_ondblclick3");

driver.manage().window().maximize();

driver.switchTo().frame("iframeResult"); // switch to frame

WebElement f1=driver.findElement(By.xpath("//input[@id='field1']"));

f1.clear();

f1.sendKeys("Welcome");

WebElement button=driver.findElement(By.xpath("//button[normalize-space()='Copy
Text']"));

Actions act=new Actions(driver);

act.doubleClick(button).perform(); // double click action

//validation

WebElement f2=driver.findElement(By.xpath("//input[@id='field2']"));

//String copiedtext=f2.getText(); // will not work

String copiedtext=f2.getAttribute("value"); // this will work

System.out.println("Copied text is:"+copiedtext);

if(copiedtext.equals("Welcome"))
{

System.out.println("test passed");

else

System.out.println("test failed");

}}}

37.Actions vs Action

package day29;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Action;

import org.openqa.selenium.interactions.Actions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class ActionsVsAction {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

WebDriver driver =new ChromeDriver();

driver.get("http://swisnl.github.io/jQuery-contextMenu/demo.html");

driver.manage().window().maximize();

WebElement button=driver.findElement(By.xpath("//span[@class='context-menu-one
btn btn-neutral']"));
Actions act=new Actions(driver);

//act.contextClick(button).build().perform();

Action myaction=act.contextClick(button).build(); // creating action and storing it in


variable

myaction.perform(); // completing action

//act.contextClick(button).perform(); //right click

38.Tabs and Windows

package day30;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WindowType;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class TabsAndWindows {

public static void main(String[] args) {


WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().window().maximize();

driver.get("https://www.opencart.com/");

driver.switchTo().newWindow(WindowType.TAB); // OPENS NEW TAB

//driver.switchTo().newWindow(WindowType.WINDOW); // OPENS IN ANOTHER


WINDOW

driver.get("https://opensource-demo.orangehrmlive.com/");

39.KeyBoard actions

package day30;

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.Keys;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import io.github.bonigarcia.wdm.WebDriverManager;
public class KeyboardActions {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://text-compare.com/");

driver.findElement(By.xpath("//textarea[@id='inputText1']")).sendKeys("WELCOME TO
AUTOMATION");

Actions act=new Actions(driver);

//ctrl +a

act.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();

//ctrl +c

act.keyDown(Keys.CONTROL).sendKeys("c").keyUp(Keys.CONTROL).perform();

//tab

act.keyDown(Keys.TAB).keyUp(Keys.TAB).perform();

//act.sendKeys(Keys.TAB).perform(); // only if want to press single key then prefer this

//ctrl+v
act.keyDown(Keys.CONTROL).sendKeys("v").keyUp(Keys.CONTROL).perform();

40.JavaScript Executor

package day30;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class InteractwithElementsUsingJS {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

//ChromeDriver driver=new ChromeDriver();

driver.get("https://testautomationpractice.blogspot.com/");

driver.manage().window().maximize();

driver.switchTo().frame(0);
JavascriptExecutor js=(JavascriptExecutor) driver;

//JavascriptExecutor js=driver;

//First name - inputbox

WebElement inputbox=driver.findElement(By.id("RESULT_TextField-1"));

js.executeScript("arguments[0].setAttribute('value','john')", inputbox);

//Radio button

WebElement male_Rd=driver.findElement(By.id("RESULT_RadioButton-7_0"));

//male_Rd.click(); //ClickInterceptedException

js.executeScript("arguments[0].click();",male_Rd);

//Checkbox

WebElement chkbox=driver.findElement(By.id("RESULT_CheckBox-8_0"));

js.executeScript("arguments[0].click();",chkbox);

//button

WebElement button=driver.findElement(By.id("FSsubmit"));

js.executeScript("arguments[0].click();",button);

}}

41.Scrolling Page

package day30;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;

public class ScrollingPage {

public static void main(String[] args) throws InterruptedException {

WebDriverManager.chromedriver().setup();

ChromeDriver driver=new ChromeDriver();

driver.get("https://www.countries-ofthe-world.com/flags-of-the-world.html");

driver.manage().window().maximize();

JavascriptExecutor js=driver;

//1) scroll down page by pixel

//js.executeScript("window.scrollBy(0,3000)", "");

//System.out.println(js.executeScript("return window.pageYOffset;")); //3000

//2) scroll down the page till the element is present

//WebElement flag=driver.findElement(By.xpath("//img[@alt='Flag of India']"));

//js.executeScript("arguments[0].scrollIntoView();", flag);

//System.out.println(js.executeScript("return window.pageYOffset;")); //5077.40234375

//3) scroll down till end of the page/document

js.executeScript("window.scrollBy(0,document.body.scrollHeight)");

System.out.println(js.executeScript("return window.pageYOffset;"));

Thread.sleep(3000);
// go back to initial position

js.executeScript("window.scrollBy(0,-document.body.scrollHeight)");

42.Broken Links

package day31;

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.time.Duration;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class BrokenLinks {

public static void main(String[] args) throws IOException {


WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("http://www.deadlinkcity.com/");

driver.manage().window().maximize();

List<WebElement> links=driver.findElements(By.tagName("a"));

System.out.println("Total number of links:"+links.size()); //48

int brokenlinks=0;

for(WebElement linkEle:links)

String hrefAttValue=linkEle.getAttribute("href");

// pre-requisite for checking broken link

if(hrefAttValue==null || hrefAttValue.isEmpty())

System.out.println("href attribute value is empty.");

continue;

//Checking link is broken or not

URL linkurl=new URL(hrefAttValue); // convert String --> URL format

HttpURLConnection conn=(HttpURLConnection) linkurl.openConnection();


////send request to server - open , connect

conn.connect();

if(conn.getResponseCode()>=400)
{

System.out.println(hrefAttValue+" "+"====> Broken Link");

brokenlinks++;

else

System.out.println(hrefAttValue+" "+"====> Not Broken Link");

System.out.println("total number of broken links:"+brokenlinks);

43.Capture Screen Shots

package day31;

import java.io.File;

import java.io.IOException;

import java.time.Duration;

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.By;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class CaptureScreenshot {

public static void main(String[] args) throws IOException {

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://demo.nopcommerce.com/");

driver.manage().window().maximize();

//Capture full page screenshot - selenium 3 & 4

/*TakesScreenshot ts=(TakesScreenshot)driver;

File src=ts.getScreenshotAs(OutputType.FILE);

File trg=new
File("C:\\Users\\pavan\\Aug19Batch\\seleniumproject\\screenshots\\fullpage.png");

FileUtils.copyFile(src, trg);

*/

// capture screenshot of specific area from webpage -- selenium 4+

/*WebElement featuredproducts=driver.findElement(By.xpath("//div[@class='product-
grid home-page-product-grid']"));

File src=featuredproducts.getScreenshotAs(OutputType.FILE);

File trg=new
File("C:\\Users\\pavan\\Aug19Batch\\seleniumproject\\screenshots\\featureproducts.png");

FileUtils.copyFile(src, trg);
*/

// capture screenshot of specific Web element -- selenium 4+

WebElement logo=driver.findElement(By.xpath("//img[@alt='nopCommerce
demo store']"));

File src=logo.getScreenshotAs(OutputType.FILE);

File trg=new
File("C:\\Users\\pavan\\Aug19Batch\\seleniumproject\\screenshots\\logo.png");

FileUtils.copyFile(src, trg);

44.Headless Testing

package day31;

import java.net.SocketException;

import java.time.Duration;

import java.util.NoSuchElementException;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.edge.EdgeDriver;

import org.openqa.selenium.edge.EdgeOptions;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.FluentWait;

import org.openqa.selenium.support.ui.Wait;

import org.openqa.selenium.support.ui.WebDriverWait;

import com.google.common.base.Function;

import io.github.bonigarcia.wdm.WebDriverManager;

public class HeadlessTesting {

public static void main(String[] args) throws InterruptedException {

//////// chrome browser ///////////

//Appraoch1) Headless mode

/*ChromeOptions options=new ChromeOptions();

options.setHeadless(true);

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver(options);

*/

//Appraoch2) WDM 5.1+

//ChromeOptions options=new ChromeOptions();

//options.setHeadless(true);
//WebDriver driver=WebDriverManager.chromedriver().capabilities(options).create();

////////// edge browser /////////////

//Appraoch1

/*EdgeOptions options=new EdgeOptions();

options.setHeadless(true);

WebDriverManager.edgedriver().setup();

WebDriver driver=new EdgeDriver(options);

*/

//Appraoch 2

EdgeOptions options=new EdgeOptions();

options.setHeadless(true);

WebDriver driver=WebDriverManager.edgedriver().capabilities(options).create();

driver.get("https://opensource-demo.orangehrmlive.com/");

Thread.sleep(3000);

driver.findElement(By.name("username")).sendKeys("Admin");

driver.findElement(By.name("password")).sendKeys("admin123");

driver.findElement(By.xpath("//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/form/div[3]/butt
on")).click();

// validation
String act_title=driver.getTitle();

String exp_title="OrangeHRM";

if(act_title.equals(exp_title))

System.out.println("Login test passed");

else

System.out.println("Login Test failed");

//7. close browser

driver.quit();

You might also like