Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Tuesday, October 1, 2024

Run two browsers simultaneously in Selenium

 package TEST;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.firefox.FirefoxDriver;


public class Selenium_Latest {


public static void main(String[] args) {

// Create and start two threads, one for each browser.

Thread chromeThread = new Thread(new BrowserRunnable("chrome"));

Thread firefoxThread = new Thread(new BrowserRunnable("firefox"));


chromeThread.start();

firefoxThread.start();

}


}


// Runnable class for launching a browser

class BrowserRunnable implements Runnable {

private String browserType;


public BrowserRunnable(String browserType) {

this.browserType = browserType;

}


@Override

public void run() {

WebDriver driver = null;


if (browserType.equals("chrome")) {

driver = new ChromeDriver();

} else if (browserType.equals("firefox")) {

driver = new FirefoxDriver();

}


if (driver != null) {

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


// Optionally, get the title and print it for each browser

String title = driver.getTitle();

System.out.println(browserType + " Browser - Page Title: " + title);


// Closing the browser after operation

driver.quit();

}

}

}

Monday, July 29, 2024

Selenium XPath in detail

What is XPATH?

  • It is an XML path.
  • It is one of the locator types in selenium.
  • It uses path expression to navigate in XML documents and to identify a node or number of nodes.
  • XPath is used to handle complex and dynamic paths.
 

Types of XPATH in Selenium:

  1. Absolute XPath
  2. Relative XPath
 

What is Absolute XPath?

  • Absolute path starts from <HTML> tag.
  • It uses / ( forward slash ).
  • It is used to identify any element direct way by consider all the tag starts from <HTML> tag.
  • It is much more faster than "Relative xpath" as it holds the direct path to the target node/tag/element from start <Html> tag.
  • But we will mostly use this one if it holds a long string path and is difficult to maintain or handle. It is not a shortend path.
 

What is Relative XPath?

  • It uses //  ("forward double slash").
  • It will consider any node/element/tag as a refernce point from where either we can traverse forard or reverse direction to identify target node/tag.
  • It is mostly used as we are considering any node as a reference node (stable node) from a DOM.

Saturday, July 27, 2024

Java Selenium Script to Extract Two Numbers from a Web Page Automatically

 package system;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;

public class Practice {

   WebDriver driver;

@BeforeMethod
public void setUp() {
  WebDriverManager.chromedriver().setup();
  driver = new ChromeDriver();
}

@Test(description = "extraction of two numbers from a web page")
public void test() throws InterruptedException {

driver.get("https://ultimateqa.com/complicated-page");

// Locate the element containing the CAPTCHA question
WebElement captchaElement = driver.findElement(By.className("et_pb_contact_captcha_question"));

// Extract the CAPTCHA question text
String captchaText = captchaElement.getText().trim(); // Example: "5 + 6"

// Split the text to get the operands
String[] parts = captchaText.split("\\+");
int firstNumber = Integer.parseInt(parts[0].trim());
int secondNumber = Integer.parseInt(parts[1].trim());

// Calculate the sum
int sum = firstNumber + secondNumber;

// Print the sum (for debugging purposes)
System.out.println("Extracted Numbers: " + firstNumber + " + " + secondNumber + " = " + sum);

// Enter the sum into the CAPTCHA input field
WebElement captchaInputField = driver.findElement(By.className("et_pb_contact_captcha"));
captchaInputField.sendKeys(String.valueOf(sum));
}
}

Monday, July 15, 2024

Selenium Interview Questions and Answers - PART 2

1. WebDriver is interface or class?
  • WebDriver is an interface in Selenium.
2. If we do not add a driver exe file what will happen and what kind of exception will be generated?
  • If the driver executable is not added, Selenium won't be able to communicate with the browser, and a WebDriverException will be thrown.
3. What is the difference between close and quit?
  • close(): Closes the current browser window.
  • quit(): Closes all the browser windows and ends the WebDriver session.
4. Difference between get and navigate().to() ?
  • get(): Loads a new web page in the current browser window.
  • navigate().to(): This does the same as get() but allows for additional navigation options like back, forward, and refresh.
5. Difference between findElement and findElements?
  • findElement: Returns a single WebElement or throws  NoSuchElementException if not found.
  • findElements: Returns a list of WebElements. If no elements are found, it returns an empty list.
6. How do you get all the links on the current page? Which locator will you use other than XPath?
  • You can use the CSS selector a to find all links.
List<WebElement> links = driver.findElements(By.cssSelector("a"));

7. Methods of WebDriver?
  • Some common methods are: get() , getCurrentUrl() , getTitle(), findElement() , findElements() , getPageSource() , close() , quit(), navigate() , manage() .
8. What is the use of the getCurrentPageSource method?
  • It returns the source code of the current page.
9. When do we go for the findElements method and what is the return type?
  • Use findElements when you expect multiple elements. It returns a list of WebElements.
10. Why do we get WebDriverException?
  • This exception is thrown when WebDriver is unable to interact with the browser. Possible reasons include incorrect WebDriver setup, browser crashes, or network issues.
11. Absolute and Relative XPath?
  • Absolute XPath: Starts from the root and follows a complete path (e.g., /html/body/div ).
  • Relative XPath: Starts from the middle of the HTML DOM structure (e.g., //div[@id='example'] ).

Monday, June 10, 2024

How to Handle Checkboxes in Selenium

 package com.system.patternz;

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.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;

public class Practice {
WebDriver driver;

@BeforeMethod
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://testautomationpractice.blogspot.com/");
driver.manage().window().maximize();
}

@Test(enabled = true, priority = 0, description = "how to select specific checkboxes")
public void test1() throws InterruptedException {
driver.findElement(By.id("sunday")).click();
Thread.sleep(3000);
}

@Test(enabled = true, priority = 1, description = "how to select all checkboxes")
public void test2() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
for (WebElement x : list) {
x.click();
}
}

@Test(enabled = true, priority = 2, description = "how to select multiple checkboxes by choice")
public void test3() throws InterruptedException {
ArrayList<String> list3 = new ArrayList<String>();
list3.add("Sunday");
list3.add("Wednesday");
list3.add("Saturday");
System.out.println(list3);
List<WebElement> list1 = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
for (WebElement x : list1) {
String str = x.getText();
for (String x1 : list3) {
if (str.equals(x1)) {
x.click();
Thread.sleep(3000);
}
}
}
}

@Test(enabled = true, priority = 3, description = "how to select multiple checkboxes by choice")
public void test4() throws InterruptedException {
List<WebElement> list1 = driver.findElements(By.xpath("//*[@class='form-group'][4]//div//input"));
for (WebElement x : list1) {
String str = x.getAttribute("id");
if (str.equals("monday") || str.equals("wednesday") || str.equals("saturday")) {
System.out.println("next click");
x.click();
Thread.sleep(3000);
} else {
System.out.println("not found");
}
}
}

@Test(enabled = true, priority = 4, description = "how to select last 2 checkboxes")
public void test5() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
int totalcheckboxes = list.size();
for (int i = totalcheckboxes - 2; i < totalcheckboxes; i++) {
list.get(i).click();
}
}

@Test(enabled = true, priority = 5, description = "how to select first 2 checkboxes")
public void test6() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
int totalcheckboxes = list.size();
for (int i = 0; i < totalcheckboxes; i++) {
if (i < 2) {
list.get(i).click();
Thread.sleep(3000);
}
}
}
}

Selenium test run without using System.setProperty in the code

 package com.system.pattern;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

import io.github.bonigarcia.wdm.WebDriverManager;


public class Practice {


WebDriver driver;


@BeforeMethod

public void setUp() {

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver();

}


@Test(description = "Selenium test run without using System.setProperty in the code")

public void test() {

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


}

}


Chrome version - 125.0.6422.141


Webdrivermanager version - 5.5.3

How to Easily Read Chrome Driver Files from the src/main/resources Folder

 package com.system.pattern;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;


public class NewTest {


WebDriver driver;


@Test(description = "chrome webdriver found under src/main/resources")

public void chrome() {


String chromeDriverPath = System.getProperty

("user.dir") + "/src/main/resources/chrome/chromedriver";

System.setProperty("webdriver.chrome.driver", chromeDriverPath);

driver = new ChromeDriver();

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


}

}

Wednesday, June 28, 2023

How to Quickly Refresh Your Browser in Selenium Java

1. Navigate the refresh method
driver. navigate().refresh();

2. Get the current URL
driver.get(driver.getCurrentUrl());

3. Javascript Executor
JavascriptExecutor executor=(JavascriptExecutor) driver;
executor.executeScript("location.reload()");

4. Robot class
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_F5);
robot.keyRelease(KeyEvent.VK_F5);

Thursday, March 30, 2023

Where Can You Find Free SELENIUM REAL TIME PROJECT Resources

 This project includes the following frameworks and libraries:
  1.  ChromeOptions
  2.  TestNG
  3.  Maven
  4.  Extent Report
  5.  Data Provider Method
  6.  Excel File Read (JXL)
  7.  Send Reports Automatically to Email
  8.  Failed Tests Screenshots
Selenium Code:

package Practice;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.lang.reflect.Method;

import java.text.SimpleDateFormat;

import java.time.Duration;

import java.util.Date;

import java.util.Properties;

import java.util.concurrent.TimeUnit;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

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.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.testng.ITestResult;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.AfterSuite;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

import com.relevantcodes.extentreports.ExtentReports;

import com.relevantcodes.extentreports.ExtentTest;

import com.relevantcodes.extentreports.LogStatus;

import jxl.Sheet;

import jxl.Workbook;

import jxl.read.biff.BiffException;

public class Selenium_Test {

public WebDriver driver;

public ExtentReports extent;

public ExtentTest extentTest;

@SuppressWarnings("deprecation")

@BeforeMethod

public void setup(Method method) {

ChromeOptions chromeOptions = new ChromeOptions();

chromeOptions.addArguments("--remote-allow-origins=*");

this.driver = new ChromeDriver(chromeOptions);

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

driver.manage().deleteAllCookies();

driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));

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

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

extentTest = extent.startTest(method.getName(), "This is a test for " + method.getName());

}

@BeforeTest(alwaysRun = true)

public void setExtent() {

extent = new ExtentReports("./test-output/Reports/Report.html", true);

extent.addSystemInfo("User Name", "Suriya");

extent.addSystemInfo("Environment", "Automation Testing");

extent.addSystemInfo("Application", "Blog");

extent.addSystemInfo("Test Scenario", "Functionality Testing");

}

public String getScreenshot(WebDriver driver, String screenshotName) throws IOException {

String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());

TakesScreenshot ts = (TakesScreenshot) driver;

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

String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/" 

+ screenshotName + dateName + ".png";

File finalDestination = new File(destination);

FileUtils.copyFile(source, finalDestination);

return destination;

}

// DATA PROVIDER METHOD in JXL

String[][] data = null;

@DataProvider(name = "loginData")

public String[][] loginDataProvider() throws BiffException, IOException {

data = getExcelData();

return data;

}

public String[][] getExcelData() throws BiffException, IOException {

FileInputStream excel = new FileInputStream("D:\\SUR\\src\\test\\resources\\login.xls");

Workbook workbook = Workbook.getWorkbook(excel);

Sheet sheet = workbook.getSheet(0);

int rowCount = sheet.getRows();

int columnCount = sheet.getColumns();

String testData[][] = new String[rowCount - 1][columnCount];

for (int i = 1; i < rowCount; i++) {

for (int j = 0; j < columnCount; j++) {

testData[i - 1][j] = sheet.getCell(j, i).getContents();

}

}

return testData;

}

@Test(enabled = true, priority = 1)

public void testExcelData() {

System.out.println("suriya");

}

@AfterMethod(alwaysRun = true)

public void Down(ITestResult result) throws IOException {

if (result.getStatus() == ITestResult.FAILURE) {

extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getName());

extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getThrowable());

String screenshotPath = getScreenshot(driver, result.getName());

extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath));

} else if (result.getStatus() == ITestResult.SKIP) {

extentTest.log(LogStatus.SKIP, "Test Case SKIPPED IS " + result.getName());

} else if (result.getStatus() == ITestResult.SUCCESS) {

extentTest.log(LogStatus.PASS, "Test Case PASSED IS " + result.getName());

}

extent.endTest(extentTest);

// driver.quit();

}

@AfterTest(alwaysRun = true)

public void endReport() {

extent.flush();

// extent.close();

}

@AfterSuite

public void sendEmailReport() {

Properties props = new Properties();

props.put("mail.smtp.host", "smtp.gmail.com");

props.put("mail.smtp.socketFactory.port", "465");

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

props.put("mail.smtp.auth", "true");

props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication("yourgmail@gmail.com", "your app password");

}

});

try {

Message message = new MimeMessage(session);

message.setFrom(new InternetAddress("your@gmail.com"));

message.setRecipients(Message.RecipientType.TO,

InternetAddress.parse("email1@gmail.com, email2@gmail.com"));

message.setSubject("Automation Testing Report");

BodyPart messageBodyPart1 = new MimeBodyPart();

messageBodyPart1.setText("This is testng report");

String[] filenames = { "D:\\SURIYA\\test-output\\emailable-report.html",

"D:\\SURIYA\\test-output\\index.html" };

Multipart multipart = new MimeMultipart();

for (String filename : filenames) {

MimeBodyPart messageBodyPart = new MimeBodyPart();

DataSource source = new FileDataSource(filename);

messageBodyPart.setDataHandler(new DataHandler(source));

messageBodyPart.setFileName(filename);

multipart.addBodyPart(messageBodyPart);

}

message.setContent(multipart);

Transport.send(message);

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

} catch (MessagingException e) {

throw new RuntimeException(e);

}

}

}

Wednesday, March 29, 2023

Webdriver Manager: A Comprehensive Overview of Its Benefits

WebDriverManager is a library in Java that allows for easy setup and management of web drivers for different browsers such as Chrome, Firefox, and Edge. The main benefits of using WebDriverManager are:

1. Automatic driver management: WebDriverManager automatically downloads the required driver binaries and sets up the system properties, making it easier to use different web drivers without manual intervention.

2. Easy setup: Using WebDriverManager eliminates the need to download and set up the web driver executable file separately. The library handles everything for you.

3. Cross-platform support: WebDriverManager supports multiple operating systems, including Windows, Mac, and Linux.

4. Integration with testing frameworks: WebDriverManager can be easily integrated with popular testing frameworks like JUnit and TestNG, allowing for seamless web driver management during test automation.

5. Improved maintenance: By using WebDriverManager, you can avoid issues related to outdated driver versions or incompatible operating systems. It helps ensure that you have the latest version of the driver, thereby reducing the maintenance effort required to keep your test automation suite up-to-date.



How To Use CROSS BROWSER TESTING IN SELENIUM WEBDRIVER

 package Practice;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.firefox.FirefoxOptions;

import org.testng.annotations.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

public class WebDriver {

@Test

public void testChrome() {

ChromeOptions chromeOptions = new ChromeOptions();

WebDriverManager.chromedriver().setup();

ChromeDriver driver = new ChromeDriver(chromeOptions);

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

driver.quit();

}

@Test

public void testFirefox() {

FirefoxOptions firefoxOptions = new FirefoxOptions();

WebDriverManager.firefoxdriver().setup();

FirefoxDriver driver = new FirefoxDriver(firefoxOptions);

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

driver.quit();

}

}


testng.xml file:

<suite name="My Test Suite" parallel="tests">

<test name="Chrome Test">

<classes>

<class name="Practice.WebDriver">

<methods>

<include name="testChrome" />

</methods>

</class>

</classes>

</test>

<test name="Firefox Test">

<classes>

<class name="Practice.WebDriver">

<methods>

<include name="testFirefox" />

</methods>

</class>

</classes>

</test>

</suite>

Tuesday, March 28, 2023

Quick & Easy Method to Send TestNG Reports via Email in Selenium WebDriver

package Practice;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class SendMailSSLWithAttachment {

public static void main(String[] args) {

// Create object of Property file

Properties props = new Properties();

// this will set host of server- you can change based on your requirement

props.put("mail.smtp.host", "smtp.gmail.com");

// set the port of socket factory

props.put("mail.smtp.socketFactory.port", "465");

// set socket factory

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

// set the authentication to true

props.put("mail.smtp.auth", "true");

// set the port of SMTP server

props.put("mail.smtp.port", "465");

// This will handle the complete authentication

Session session = Session.getDefaultInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication("youremail@gmail.com", "email-app-password");

}

});

try {

// Create object of MimeMessage class

Message message = new MimeMessage(session);

// Set the from address

message.setFrom(new InternetAddress("from@gmail.com"));

// Set the recipient address

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("s@gmail.com"));

// Add the subject link

message.setSubject("Automation Testing Report");

// Create object to add multimedia type content

BodyPart messageBodyPart1 = new MimeBodyPart();

// Set the body of email

messageBodyPart1.setText("This is testng report");

// Create another object to add another content

MimeBodyPart messageBodyPart2 = new MimeBodyPart();

// Mention the file which you want to send

String filename = "D:\\SURIYA\\test-output\\emailable-report.html";

// Create data source and pass the filename

DataSource source = new FileDataSource(filename);

// set the handler

messageBodyPart2.setDataHandler(new DataHandler(source));

// set the file

messageBodyPart2.setFileName(filename);

// Create object of MimeMultipart class

Multipart multipart = new MimeMultipart();

// add body part 1

multipart.addBodyPart(messageBodyPart2);

// add body part 2

multipart.addBodyPart(messageBodyPart1);

// set the content

message.setContent(multipart);

// finally send the email

Transport.send(message);

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

} catch (MessagingException e) {

throw new RuntimeException(e);

}

}

}

NOTE:

  1. Download this repository
  • https://mvnrepository.com/artifact/javax.mail/javax.mail-api/1.6.2
  • https://mvnrepository.com/artifact/com.sun.mail/javax.mail/1.6.2
  • https://mvnrepository.com/artifact/javax.activation/activation/1.1.1