(2-8)
2 - Implement Web Drivers on various Browsers
import java.awt.Desktop;
import java.net.URI;
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
String url;
System.out.print("Enter the URL : ");
url = scanner.nextLine();
while (true) {
System.out.println("\nChoose a browser to open the URL:");
System.out.println("1. Default System Browser");
System.out.println("2. Open with Chrome (if installed)");
System.out.println("3. Open with Firefox (if installed)");
System.out.println("4. Exit");
Int choice = scanner.nextInt();
scanner.nextLine();
try {
switch (choice) {
case 1:
openDefaultBrowser(url);
break;
case 2:
openWithBrowser("chrome", url);
break;
case 3:
openWithBrowser("firefox", url);
break;
case 4:
System.out.println("Exiting application...");
return;
default:
System.out.println("Invalid choice. Please try again.");
}
} catch (Exception e) {
System.out.println("Error opening browser: " + e.getMessage());
}
}
} public static void openDefaultBrowser(String url) throws Exception {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(new URI(url));
System.out.println("Opened in default browser.");
} else {
throw new UnsupportedOperationException("Desktop is not supported.");
}
}public static void openWithBrowser(String browser, String url) throws Exception {
String command = "";
if (browser.equalsIgnoreCase("chrome")) {
command = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
} else if (browser.equalsIgnoreCase("firefox")) {
command = "C:\\Program Files\\Mozilla Firefox\\firefox.exe";
}
Runtime.getRuntime().exec(new String[] {command, url});
System.out.println("Opened with " + browser);
}
}
3 - Implement and demonstrate LOCATOR commands
Code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Assignment3 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\mca24064\\chromedriver-win64\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// 1. Valid login using ID locator (saucedemo.com)
driver.get("https://www.saucedemo.com/");
Thread.sleep(1000);
driver.findElement(By.id("user-name")).sendKeys("standard_user");
driver.findElement(By.id("password")).sendKeys("secret_sauce");
driver.findElement(By.id("login-button")).click();
Thread.sleep(3000);
// 2. Invalid login using name, className, tagName
driver.get("https://www.facebook.com/login/");
Thread.sleep(1000);
driver.findElement(By.name("email")).sendKeys("wrongUser");
driver.findElement(By.name("pass")).sendKeys("wrongPass");
driver.findElement(By.tagName("button")).click();
Thread.sleep(3000);
// 3. Retrieve and print username/password (Demo on saucedemo again)
driver.get("https://www.saucedemo.com/");
WebElement userField = driver.findElement(By.id("user-name"));
WebElement passField = driver.findElement(By.id("password"));
userField.sendKeys("Jaba");
passField.sendKeys("Password123");
String userVal = userField.getAttribute("value");
String passVal = passField.getAttribute("value");
System.out.println("Entered Username: " + userVal);
System.out.println("Entered Password: " + passVal);
Thread.sleep(2000);
// 4. Fill Facebook signup form
driver.get("https://www.facebook.com/r.php");
Thread.sleep(2000);
driver.findElement(By.name("firstname")).sendKeys("Jaba");
driver.findElement(By.name("lastname")).sendKeys("Jaba");
driver.findElement(By.name("reg_email__")).sendKeys("jaba@example.com");
driver.findElement(By.name("reg_passwd__")).sendKeys("Password@123");
driver.findElement(By.id("day")).sendKeys("23");
driver.findElement(By.id("month")).sendKeys("Jul");
driver.findElement(By.id("year")).sendKeys("2003");
driver.findElement(By.xpath("//label[text()='Male']")).click();
Thread.sleep(3000);
// 5. Verify Google logo using CSS Selector
driver.get("https://www.google.com");
Thread.sleep(2000);
boolean logoPresent = driver.findElement(By.cssSelector("img.lnXdpd")).isDisplayed();
System.out.println("Google logo displayed: " + logoPresent);
// 6. Gmail login using XPath (email field only due to security)
driver.get("https://accounts.google.com/signin");
Thread.sleep(2000);
driver.findElement(By.xpath("//input[@type='email']")).sendKeys("jaba@gmail.com");
driver.findElement(By.xpath("//span[text()='Next']")).click();
Thread.sleep(3000);
// Password step is protected and should not be automated for real accounts
// 7. Facebook "Forgot Password" using link text
driver.get("https://www.facebook.com/");
Thread.sleep(2000);
driver.findElement(By.linkText("Forgotten password?")).click();
Thread.sleep(2000);
driver.findElement(By.name("email")).sendKeys("jaba@gmail.com.com");
Thread.sleep(3000);
// Close browser
driver.quit();
}
}
4 - Implementation of Browser Commands & Navigation Command
Invoke any Browser ---
Open any URL of your own choice:
Get Page Title name and Title length
Print Page Title and Title length on the Eclipse Console
Get page Source and Page Source length
Print page Length on Eclipse Console.
Close the Browser
Navigation Commands ---
Invoke any Browser
Navigate to URL of your own choice
Navigate to any other website you own choice.
Come back to the Home page using the back command
Again go back to the website using forward command
Refresh the Browser using Refresh command
Close the Browser
Code:
import java.util.Scanner;
import org.openqa.selenium.chrome.ChromeDriver;
public class A4 {
public static void main(String[] args) throws InterruptedException {
Scanner s = new Scanner(System.in);
ChromeDriver driver = new ChromeDriver();
System.out.print("Functionalities: \n"
+ "1. Basic Browser Commands\n"
+ "2. Navigation Commands\n"
+ "Enter your choice: ");
int ch = s.nextInt();
// Case 1: Browser Commands
if (ch == 1) {
driver.get("https://www.saucedemo.com/v1/");
String title = driver.getTitle();
int titleLength = title.length();
System.out.println("\nTitle of the Current Page: " + title);
System.out.println("Length of the Title: " + titleLength);
String src = driver.getPageSource();
int srcLength = src.length();
System.out.println("\nRetrieved Page Source: " + src);
System.out.println("Length of Page Source: " + srcLength);
driver.close();
}
else if (ch == 2) {
System.out.println("\nLanding on first page...");
driver.navigate().to("https://www.saucedemo.com/v1/");
Thread.sleep(5000);
System.out.println("Landing on second page...");
driver.navigate().to("https://practicetestautomation.com/practice-test-login/");
Thread.sleep(5000);
System.out.println("Going backward...");
driver.navigate().back();
Thread.sleep(5000);
System.out.println("Going forward...");
driver.navigate().forward();
Thread.sleep(5000);
System.out.println("Refreshing...");
driver.navigate().refresh();
Thread.sleep(5000);
System.out.println("Closing browser...");
driver.close();
}
else {
System.out.println("Invalid choice! Please run again.");
driver.close();
}
s.close();
}
}
5 - the implementation of different wait methods in Selenium.
Code:
import java.time.Duration;
import java.util.NoSuchElementException;
import java.util.Scanner;
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.WebDriverWait;
import com.google.common.base.Function;
import org.openqa.selenium.support.ui.Wait;
public class SeleniumMethods {
private static final String URL = "https://www.saucedemo.com/v1/";
private static final String USERNAME = "standard_user";
private static final String PASSWORD = "secret_sauce";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("\n=== Selenium Waits Demo ===");
System.out.println("1. Implicit Wait");
System.out.println("2. Explicit Wait");
System.out.println("3. Fluent Wait");
System.out.println("4. Hard Wait (Thread.sleep)");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
switch (choice) {
case 1 -> implicitWaitDemo();
case 2 -> explicitWaitDemo();
case 3 -> fluentWaitDemo();
case 4 -> hardWaitDemo();
case 5 -> {
System.out.println("Exiting...");
sc.close();
System.exit(0);
}
default -> System.out.println("Invalid choice! Try again.");
}
}
}
private static WebDriver setupDriver() {
System.setProperty("webdriver.chrome.driver", "D:\\Jaba\\chromedriver-win64\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
return driver;
}
private static void login(WebDriver driver) {
driver.get(URL);
driver.findElement(By.id("user-name")).sendKeys(USERNAME);
driver.findElement(By.id("password")).sendKeys(PASSWORD);
driver.findElement(By.id("login-button")).click();
}
private static void implicitWaitDemo() {
WebDriver driver = setupDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
login(driver);
WebElement product = driver.findElement(By.className("inventory_item_name"));
System.out.println("Implicit Wait found product: " + product.getText());
driver.quit();
}
private static void explicitWaitDemo() {
WebDriver driver = setupDriver();
login(driver);
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement cart = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("shopping_cart_link")));
System.out.println("Explicit Wait found cart icon displayed: " + cart.isDisplayed());
driver.quit();
}
private static void fluentWaitDemo() {
WebDriver driver = setupDriver();
login(driver);
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(15))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
WebElement menuBtn = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("react-burger-menu-btn"));
}
});
System.out.println("Fluent Wait found menu button: " + menuBtn.getText());
driver.quit();
}
private static void hardWaitDemo() {
WebDriver driver = setupDriver();
login(driver);
try {
Thread.sleep(5000); // Hard wait for 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
WebElement product = driver.findElement(By.className("inventory_item_name"));
System.out.println("Hard Wait found product: " + product.getText());
driver.quit();
}
6 - the implementation of different Alerts in Seleniums
Code:
import java.util.Scanner;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumAlert {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Jaba\\chromedriver-win64\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Selenium Alert Demo Menu ---");
System.out.println("1. Simple Alert");
System.out.println("2. Confirmation Alert");
System.out.println("3. Prompt Alert");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
// Simple Alert
driver.findElement(By.xpath("//button[text()='Click for JS Alert']")).click();
Alert simpleAlert = driver.switchTo().alert();
System.out.println("Simple Alert Text: " + simpleAlert.getText());
Thread.sleep(2000);
simpleAlert.accept();
break;
case 2:
driver.findElement(By.xpath("//button[text()='Click for JS Confirm']")).click();
Alert confirmAlert = driver.switchTo().alert();
System.out.println("Confirmation Alert Text: " + confirmAlert.getText());
Thread.sleep(2000);
confirmAlert.dismiss(); // You can also use accept()
break;
case 3:
driver.findElement(By.xpath("//button[text()='Click for JS Prompt']")).click();
Alert promptAlert = driver.switchTo().alert();
System.out.println("Prompt Alert Text: " + promptAlert.getText());
Thread.sleep(2000);
promptAlert.sendKeys("STQA Selenium Test");
promptAlert.accept();
break;
case 4:
System.out.println("Exiting program...");
break;
default:
System.out.println("Invalid choice! Try again.");
}
} while (choice != 4);
driver.quit();
sc.close();
}}
7 - Application performs different operations on Dropdown list in Selenium.
Code:
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 java.util.List;
import java.util.Scanner;
public class SeleniumDropDown {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Jaba\\chromedriver-win64\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://the-internet.herokuapp.com/dropdown");
WebElement dropdownElement = driver.findElement(By.id("dropdown"));
Select dropdown = new Select(dropdownElement);
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Selenium Dropdown Demo Menu ---");
System.out.println("1. Select by Index");
System.out.println("2. Select by Value");
System.out.println("3. Select by Visible Text");
System.out.println("4. Print all Options");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
dropdown.selectByIndex(1); // Select Option 1
System.out.println("Selected option by Index: " + dropdown.getFirstSelectedOption().getText());
break;
case 2:
dropdown.selectByValue("2"); // Select Option 2
System.out.println("Selected option by Value: " + dropdown.getFirstSelectedOption().getText());
break;
case 3:
dropdown.selectByVisibleText("Option 1");
System.out.println("Selected option by Visible Text: " + dropdown.getFirstSelectedOption().getText());
break;
case 4:
List<WebElement> options = dropdown.getOptions();
System.out.println("Available Options in Dropdown:");
for (WebElement opt : options) {
System.out.println(opt.getText());
}
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Try again.");
}
Thread.sleep(2000);
} while (choice != 5);
driver.quit();
sc.close();
}
}
8 - Application that demonstrates the implementation handling frames in Selenium
Code:
package assignment8;
import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumFrame {
public static void main(String[] args) throws InterruptedException {
// Set ChromeDriver path
System.setProperty("webdriver.chrome.driver", "D:\\Jaba\\chromedriver-win64\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// Open DemoQA Frames page
driver.get("https://demoqa.com/frames");
// Wait for page to load frames
driver.manage().timeouts().implicitlyWait(java.time.Duration.ofSeconds(5));
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Selenium Frame Handling Menu (DemoQA) ---");
System.out.println("1. Switch to Frame1");
System.out.println("2. Switch to Frame2");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
driver.switchTo().frame("frame1");
WebElement frame1Heading = driver.findElement(By.id("sampleHeading"));
System.out.println("Frame1 Text: " + frame1Heading.getText());
driver.switchTo().defaultContent();
break;
case 2:
driver.switchTo().frame("frame2");
WebElement frame2Heading = driver.findElement(By.id("sampleHeading"));
System.out.println("Frame2 Text: " + frame2Heading.getText());
driver.switchTo().defaultContent();
break;
case 3:
System.out.println("Exiting program...");
break;
default:
System.out.println("Invalid choice! Try again.");
}
Thread.sleep(2000);
} while (choice != 3);
driver.quit();
sc.close();
}
}
| |