ertainly!
Here’s a detailed explanation of common Java Selenium programs, including their
C
purpose and functionality. Each example demonstrates a specific aspect of Selenium
WebDriver.
1. Launching a Browser
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LaunchBrowser {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.quit();
}
}
Explanation:
Imports: We import the necessary Selenium classes.
●
● WebDriver Setup: System.setPropertysets the pathto the ChromeDriver
executable, which is required to control the Chrome browser.
● Browser Launch: A new instance of Chrome is createdwith new ChromeDriver()
.
driver.get()opens the specified URL.
● Navigation:
driver.quit()closes the browser and endsthe WebDriver session.
● Cleanup:
2. Finding an Element by ID
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElementById {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("elementId")).click();
driver.quit();
}
}
Explanation:
● E
lement Interaction: This example demonstrates howto find an HTML element using
idattribute and perform a click action.
its
● F driver.findElement(By.id("elementId"))locates the element
ind Element:
with the specified ID.
click()method simulates a mouse clickon the identified element.
● Action: The
3. Finding an Element by Name
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElementByName {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.name("elementName")).sendKeys("Text");
driver.quit();
}
}
Explanation:
T
● nameattribute and send text to it.
ext Input: Here, we locate an element by its
● sendKeys: This method simulates typing text into aninput field.
4. Finding an Element by Class Name
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElementByClassName {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.className("className")).click();
driver.quit();
}
}
Explanation:
C
● classattribute.
lass Name: This program demonstrates finding an elementby its
● Click Action: Clicking on an element identified byclass name.
5. Finding an Element by CSS Selector
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElementByCss {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.cssSelector(".className")).click();
driver.quit();
}
}
Explanation:
● C SS Selectors: This example shows how to use CSS selectorsto find an element and
click it.
".className"selects elements withthe specified class.
● Selector Syntax:
6. Finding an Element by XPath
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElementByXPath {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.xpath("//button[text()='Click
me']")).click();
driver.quit();
}
}
Explanation:
X
● Path: This program uses XPath to locate an elementbased on its text.
● Element Click: It clicks on a button with specifictext.
7. Sending Keyboard Input
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SendKeysExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("inputField")).sendKeys("Hello,
World!");
driver.quit();
}
}
Explanation:
● Input Simulation: This example demonstrates how tosend keyboard input to a specific
input field.
● sendKeys Method: It simulates typing text into aninput field identified by its ID.
8. Retrieving Text from an Element
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetTextExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
String text =
driver.findElement(By.id("textElement")).getText();
System.out.println(text);
driver.quit();
}
}
Explanation:
● T ext Retrieval: This program retrieves the visibletext from an element and prints it to
the console.
● getText Method: It extracts the text content froman HTML element.
9. Handling Drop-downs
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class HandleDropdown {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
Select dropdown = new
Select(driver.findElement(By.id("dropdownId")));
dropdown.selectByVisibleText("Option 1");
driver.quit();
}
}
Explanation:
D
● rop-down Handling: This example shows how to interactwith a drop-down menu.
Selectclass is used to select optionsfrom a drop-down element.
● Select Class: The
10. Navigating Back and Forward
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class NavigateBrowser {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.get("http://anotherexample.com");
driver.navigate().back();
driver.navigate().forward();
driver.quit();
}
}
Explanation:
● B rowser Navigation: This example demonstrates howto navigate back and forth
between web pages.
● navigate() Method: This method allows you to movethrough the browser history.
11. Using Implicit Wait
java
opy code
C
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplicitWaitExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
driver.get("http://example.com");
driver.quit();
}
}
Explanation:
Implicit Wait: Sets a global wait time for findingelements before throwing an exception.
●
● manage().timeouts(): Configures the WebDriver to waitfor a specified amount of time.
12. Using Explicit Wait
java
Copy code
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;
public class ExplicitWaitExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("buttonId")))
.click();
driver.quit();
}
}
Explanation:
E
● xplicit Wait: Waits for a specific condition to occurbefore proceeding.
● WebDriverWait: This class is used to define the maximumwait time.
13. Handling Alerts
java
Copy code
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandleAlert {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("alertButton")).click();
Alert alert = driver.switchTo().alert();
alert.accept();
driver.quit();
}
}
Explanation:
A
● lert Handling: This program demonstrates how to handleJavaScript alerts.
● switchTo().alert(): Switches the context to the alertto perform actions like accepting or
dismissing it.
14. Taking a Screenshot
java
Copy code
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class ScreenshotExample {
public static void main(String[] args) throws IOException {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
File screenshot = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
driver.quit();
}
}
Explanation:
● S creenshot Capture: This example captures a screenshotof the current browser
window.
● TakesScreenshot Interface: Used to take a screenshotin the specified format.
15. Handling Iframes
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandleIframe {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.switchTo().frame("iframeName");
driver.findElement(By.id("buttonInsideIframe")).click();
driver.switchTo().defaultContent();
driver.quit();
}
}
Explanation:
● Iframe Handling: Demonstrates how to switch contextto an iframe to interact with
elements inside it.
● switchTo().frame(): Switches the context to the specifiediframe, and
switchTo().defaultContent()returns to the main document.
16. Switching Windows
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
public class SwitchWindow {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
String mainWindow = driver.getWindowHandle();
driver.findElement(By.id("newWindowButton")).click();
Set<String> allWindows = driver.getWindowHandles();
for (String window : allWindows) {
if (!window.equals(mainWindow)) {
driver.switchTo().window(window);
break;
}
}
driver.quit();
}
}
Explanation:
W
● indow Management: This program opens a new windowand switches to it.
● getWindowHandles(): Retrieves the handles of all openwindows, allowing you to
switch to a specific one.
17. File Upload
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FileUpload {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("uploadField")).sendKeys("path/to/file.txt");
driver.quit();
}
}
Explanation:
F
● ile Upload: Demonstrates how to upload a file usingthe sendKeysmethod.
● File Path: The path to the file is provided directlyto the file input element.
18. Waiting for Page Load
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class WaitForPageLoad {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
// Wait for the page to load completely (implicit wait can
also be set)
driver.manage().timeouts().pageLoadTimeout(10,
TimeUnit.SECONDS);
driver.quit();
}
}
Explanation:
● P age Load Timeout: Sets a maximum wait time for thepage to load before throwing an
exception.
● manage().timeouts(): Allows configuration of varioustimeout settings for the WebDriver.
19. JavaScript Execution
java
Copy code
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class JavaScriptExecution {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('Hello, World!');");
driver.quit();
}
}
Explanation:
J
● avaScript Executor: Executes JavaScript code withinthe context of the current page.
● Alert Creation: This example demonstrates creatinga JavaScript alert.
20. Getting Browser Window Size
java
Copy code
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetWindowSize {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
Dimension size = driver.manage().window().getSize();
System.out.println("Width: " + size.getWidth() + ", Height: "
+ size.getHeight());
driver.quit();
}
}
Explanation:
W
● indow Size: Retrieves and prints the dimensions ofthe browser window.
● Dimension Class: Represents the width and height ofthe window.
21. Setting Window Size
java
Copy code
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SetWindowSize {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.manage().window().setSize(new Dimension(1024, 768));
driver.quit();
}
}
Explanation:
S
● etting Size: This example sets the size of the browserwindow to specific dimensions.
● manage().window().setSize(): Method to change thesize of the window.
22. Maximizing the Browser Window
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MaximizeWindow {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.manage().window().maximize();
driver.quit();
}
}
Explanation:
M
● aximize: This code maximizes the browser window uponopening.
● manage().window().maximize(): Method to maximize thecurrent window.
23. Minimizing the Browser Window
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MinimizeWindow {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.manage().window().minimize();
driver.quit();
}
}
Explanation:
M
● inimize: This program minimizes the browser window.
● manage().window().minimize(): This method is usedto minimize the current window.
24. Scrolling Down the Page
java
Copy code
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScrollPage {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0, 500);");
driver.quit();
}
}
Explanation:
S
● crolling: This example scrolls down the page by aspecified number of pixels.
● JavaScript Executor: The script uses JavaScript toperform the scroll action.
25. Checking an Element’s Visibility
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CheckVisibility {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
boolean isVisible =
driver.findElement(By.id("elementId")).isDisplayed();
System.out.println("Element is visible: " + isVisible);
driver.quit();
}
}
Explanation:
● Visibility Check: This example checks whether an elementis visible on the page.
trueif the element is visible, otherwise
● isDisplayed Method: Returns false
.
26. Checking an Element’s Enable State
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CheckEnabled {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
boolean isEnabled =
driver.findElement(By.id("buttonId")).isEnabled();
System.out.println("Element is enabled: " + isEnabled);
driver.quit();
}
}
Explanation:
● E nabled State Check: Checks if an element (like abutton) is enabled and can be
interacted with.
trueif the element is enabled,otherwise
● isEnabled Method: Returns false.
27. Verifying Title of a Page
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class VerifyTitle {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
String title = driver.getTitle();
System.out.println("Page title is: " + title);
driver.quit();
}
}
Explanation:
T
● itle Verification: Retrieves and prints the titleof the current page.
● getTitle Method: Returns the title of the currentpage.
28. Verifying Current URL
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class VerifyUrl {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
String currentUrl = driver.getCurrentUrl();
System.out.println("Current URL is: " + currentUrl);
driver.quit();
}
}
Explanation:
U
● RL Verification: This example retrieves the currentURL of the page.
● getCurrentUrl Method: Returns the URL of the currentpage.
29. Waiting for an Element to be Clickable
java
Copy code
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;
public class WaitForElementToBeClickable {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("clickableEle
ment"))).click();
driver.quit();
}
}
Explanation:
● W ait for Clickable: This example waits for an elementto become clickable before
attempting to click it.
● ExpectedConditions: Provides various conditions forwaiting.
30. Handling Multiple Windows
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
public class HandleMultipleWindows {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("newWindowButton")).click();
Set<String> allWindows = driver.getWindowHandles();
for (String window : allWindows) {
driver.switchTo().window(window);
// Perform actions on the new window
}
driver.quit();
}
}
Explanation:
M
● ultiple Windows Handling: Demonstrates how to managemultiple browser windows.
● Switching Between Windows: Uses a loop to switch toeach window handle.
31. Checking if an Element is Selected (Checkbox)
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CheckIfSelected {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
boolean isSelected =
driver.findElement(By.id("checkboxId")).isSelected();
System.out.println("Checkbox is selected: " + isSelected);
driver.quit();
}
}
Explanation:
Checkbox State Check: Checks if a checkbox is selected.
●
trueif the checkbox ischecked.
● isSelected Method: Returns
32. Filling a Form
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FillForm {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com/form");
driver.findElement(By.id("firstName")).sendKeys("John");
driver.findElement(By.id("lastName")).sendKeys("Doe");
driver.findElement(By.id("submitButton")).click();
driver.quit();
}
}
Explanation:
● F orm Filling: Demonstrates how to fill out a formby locating input fields and sending
keys.
● Form Submission: Clicks the submit button after fillingthe form.
33. Using Relative XPath
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class RelativeXPath {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.xpath("//input[@name='username']")).sendKeys("us
er");
driver.quit();
}
}
Explanation:
R
● elative XPath: Uses a relative XPath to locate aninput field.
● Sending Keys: Sends keys to the located input field.
34. Using Absolute XPath
java
opy code
C
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AbsoluteXPath {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.xpath("/html/body/div/input")).sendKeys("text");
driver.quit();
}
}
Explanation:
A
● bsolute XPath: Uses an absolute XPath to locate anelement.
● Sending Keys: Sends keys to the located input field.
35. Working with Radio Buttons
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class RadioButtonExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("radioButtonId")).click();
driver.quit();
}
}
Explanation:
● Radio Button Selection: Demonstrates how to selecta radio button.
● Click Action: Clicks on the radio button to select it.
36. Using CSS Selector for Child Elements
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CssSelectorChild {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.cssSelector("div > span")).click();
driver.quit();
}
}
Explanation:
● C hild Element Selection: This example shows how touse CSS selectors to select child
elements.
● Click Action: Clicks on the child element.
37. Using JavaScript to Scroll to an Element
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScrollToElement {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();",
driver.findElement(By.id("elementId")));
driver.quit();
}
}
Explanation:
S
● croll to Element: This example scrolls the page tobring a specific element into view.
● JavaScript Executor: Executes the scroll action.
38. Handling a File Download
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.nio.file.Paths;
public class HandleFileDownload {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("download.default_directory",
Paths.get("path/to/download").toString());
WebDriver driver = new ChromeDriver(options);
driver.get("http://example.com/download");
driver.findElement(By.id("downloadButton")).click();
driver.quit();
}
}
Explanation:
F
● ile Download: Configures the download directory forfiles downloaded via the browser.
● ChromeOptions: Allows setting Chrome-specific options,including download paths.
39. JavaScript Alert Handling
java
Copy code
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandleJavaScriptAlert {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("alertButton")).click();
Alert alert = driver.switchTo().alert();
alert.accept(); // or alert.dismiss();
driver.quit();
}
}
Explanation:
● J avaScript Alert Handling: This program demonstrateshow to accept or dismiss
JavaScript alerts.
● switchTo().alert(): Switches to the alert context.
40. Verifying an Element’s Attribute
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class VerifyAttribute {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
String value =
driver.findElement(By.id("elementId")).getAttribute("attributeName");
System.out.println("Attribute value: " + value);
driver.quit();
}
}
Explanation:
A
● ttribute Verification: Retrieves the value of a specifiedattribute from an element.
● getAttribute Method: Used to obtain the attributevalue.
41. Using Actions Class for Mouse Hover
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class MouseHoverExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.id("hoverElement"))).perfo
rm();
driver.quit();
}
}
Explanation:
● M ouse Hover: Demonstrates how to perform a mouse hoveraction using the Actions
class.
● perform Method: Executes the action sequence.
42. Taking Full-Page Screenshot
java
Copy code
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class FullPageScreenshot {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
File screenshot = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new
File("fullPageScreenshot.png"));
driver.quit();
}
}
Explanation:
F
● ull-Page Screenshot: Captures a screenshot of theentire page.
● TakesScreenshot: Used for taking screenshots in Selenium.
43. Working with Dropdowns (Select Element)
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class DropdownExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
Select dropdown = new
Select(driver.findElement(By.id("dropdownId")));
dropdown.selectByVisibleText("Option 1");
driver.quit();
}
}
Explanation:
D
● ropdown Selection: Demonstrates how to select anoption from a dropdown.
● Select Class: Provides methods to interact with dropdownelements.
44. Navigating Back and Forward
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class NavigateBackAndForward {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.get("http://example.com/anotherpage");
driver.navigate().back();
driver.navigate().forward();
driver.quit();
}
}
Explanation:
● B ack and Forward Navigation: Demonstrates how to navigateback and forward in
browser history.
● navigate() Method: Used for navigation operations.
45. Page Source Retrieval
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class PageSourceExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
String pageSource = driver.getPageSource();
System.out.println(pageSource);
driver.quit();
}
}
Explanation:
P
● age Source: Retrieves the complete HTML source codeof the current page.
● getPageSource Method: Returns the page's source asa string.
46. Clearing Input Fields
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClearInputField {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("inputFieldId")).clear();
driver.quit();
}
}
Explanation:
C
● learing Input: Demonstrates how to clear text froman input field.
● clear Method: Clears the value of the specified inputfield.
47. Using Explicit Wait
java
Copy code
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;
public class ExplicitWaitExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elemen
tId")));
driver.quit();
}
}
Explanation:
E
● xplicit Wait: Waits for a specific condition to occurbefore proceeding.
● ExpectedConditions: Provides various conditions towait for.
48. Taking a Screenshot After a Failed Test
java
Copy code
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ScreenshotOnFailure {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("http://example.com");
driver.findElement(By.id("nonExistentElement")).click();
} catch (Exception e) {
File screenshot = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new
File("errorScreenshot.png"));
} finally {
driver.quit();
}
}
}
Explanation:
E
● rror Handling with Screenshot: Takes a screenshotif an exception occurs.
● try-catch-finally Block: Ensures the screenshot istaken during a failure.
49. Simulating Keyboard Actions
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class KeyboardActionsExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.id("inputFieldId")))
.click()
.sendKeys("Hello")
.sendKeys(Keys.ENTER)
.perform();
driver.quit();
}
}
Explanation:
● Keyboard Actions: Simulates typing and pressing theEnter key.
● Actions Class: Allows chaining actions for more complex interactions.
50. Using ChromeOptions for Headless Mode
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class HeadlessModeExample {
public static void main(String[] args) {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);
driver.get("http://example.com");
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
Explanation:
● H eadless Mode: Runs Chrome in headless mode, whichmeans without a graphical
user interface.
● ChromeOptions: Used to configure Chrome browser settings,including running
headless.
ere’s a set of simple Java programs, each broken down into step-by-step explanations for
H
better understanding.
1. Hello World
java
Copy code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Step-by-Step Explanation:
public class HelloWorlddefinesa class named
1. Class Declaration:
HelloWorld
.
2. M ain Method: public static void main(String[] args)is the entry point for
any Java application. This method is where the program starts executing.
3. Print Statement: System.out.println("Hello, World!");outputs the text
"Hello, World!" to the console.
2. Add Two Numbers
java
Copy code
import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("Sum: " + sum);
scanner.close();
}
}
Step-by-Step Explanation:
1. Import Scanner: import java.util.Scanner;allows us to use the Scannerclass
for user input.
2. Create Scanner Object: Scanner scanner = new Scanner(System.in);
initializes a scanner to read input from the console.
3. Input First Number: The program prompts the user toenter the first number and stores
num1
it in .
num2
4. Input Second Number: It prompts for the second numberand stores it in .
int sum = num1 + num2;adds the twonumbers.
5. Calculate Sum:
6. O System.out.println("Sum: " + sum);prints the sum to the
utput Result:
console.
7. Close Scanner: scanner.close();closes the scannerto prevent resource leaks.
3. Find the Maximum of Three Numbers
java
Copy code
import java.util.Scanner;
public class MaxOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int num3 = scanner.nextInt();
int max = Math.max(num1, Math.max(num2, num3));
System.out.println("Maximum number: " + max);
scanner.close();
}
}
Step-by-Step Explanation:
. Input Three Numbers: The user is prompted to enterthree numbers.
1
2. Calculate Maximum: The Math.max()method finds thelargest number among the
three by comparing them.
. O
3 utput Result: The maximum number is printed to the console.
4. Close Scanner: Closes the scanner.
4. Check Even or Odd
java
Copy code
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
scanner.close();
}
}
Step-by-Step Explanation:
. Input a Number: The user is prompted to enter a number.
1
2. Check Even or Odd: The program checks if the numberis even by using the modulus
operator (
%). If
number % 2 == 0
, it means the numberis even; otherwise, it is odd.
3. Output Result: It prints whether the number is evenor odd.
4. Close Scanner: Closes the scanner.
5. Calculate Simple Interest
java
Copy code
import java.util.Scanner;
public class SimpleInterest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter rate of interest: ");
double rate = scanner.nextDouble();
System.out.print("Enter time in years: ");
double time = scanner.nextDouble();
double interest = (principal * rate * time) / 100;
System.out.println("Simple Interest: " + interest);
scanner.close();
}
}
Step-by-Step Explanation:
1. Input Principal, Rate, and Time: The user inputs theprincipal amount, rate of interest,
and time in years.
2. Calculate Interest: The formula Interest=P×R×T100\text{Interest}= \frac{P \times R
\times T}{100}Interest=100P×R×Tcalculates the simple interest.
3. Output Result: The calculated interest is printedto the console.
4. Close Scanner: Closes the scanner.
6. Count Digits in a Number
java
Copy code
import java.util.Scanner;
public class CountDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int count = 0;
while (number != 0) {
number /= 10;
count++;
}
System.out.println("Number of digits: " + count);
scanner.close();
}
}
Step-by-Step Explanation:
. Input a Number: The user inputs a number.
1
whileloop divides the number by 10until it becomes 0, incrementing
2. Count Digits: A
ounteach time.
c
3. Output Result: The total number of digits is printed.
. Close Scanner: Closes the scanner.
4
7. Reverse a Number
java
Copy code
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
System.out.println("Reversed Number: " + reversed);
scanner.close();
}
}
Step-by-Step Explanation:
. Input a Number: The user inputs a number.
1
2. Reverse Logic: A whileloop extracts the last digitof the number and builds the
reversed number by shifting the previous digits.
3. Output Result: The reversed number is printed.
4. Close Scanner: Closes the scanner.
8. Check Prime Number
java
Copy code
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
System.out.println(number + " is " + (isPrime && number > 1 ?
"a prime number." : "not a prime number."));
scanner.close();
}
}
Step-by-Step Explanation:
. Input a Number: The user inputs a number.
1
2. Prime Check Logic: A forloop checks for divisibilityfrom 2 up to the square root of the
number.
3. Output Result: It prints whether the number is primeor not based on the checks.
4. Close Scanner: Closes the scanner.
9. Factorial of a Number
java
Copy code
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial: " + factorial);
scanner.close();
}
}
Step-by-Step Explanation:
.
1 Input a Number: The user inputs a number.
2. forloop multiplies all integersfrom 1 to the number.
Calculate Factorial: A
3. Output Result: The factorial result is printed.
4. Close Scanner: Closes the scanner.
10. Print Multiplication Table
java
Copy code
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number *
i));
}
scanner.close();
}
}
Step-by-Step Explanation:
1. Input a Number: The user inputs a number
4o mini
You said:
without scanner class find odd even number in java with detailed explanation
ChatGPT said:
ChatGPT
ure! Here’s a simple Java program to determine if a number is odd or even without using the
S
Scannerclass. Instead, we will use a predefined numberfor demonstration purposes.
Program: Check Even or Odd without Scanner
java
Copy code
public class EvenOdd {
public static void main(String[] args) {
// Predefined number
int number = 10; // You can change this value to test other
numbers
// Check if the number is even or odd
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
Step-by-Step Explanation
1. Class Declaration:
○ public class EvenOdddefines a class named EvenOdd .In Java, every
program must have at least one class.
2. Main Method:
○ public static void main(String[] args)is the mainmethod where
the program execution begins. It's a required entry point for all Java applications.
3. Predefined Number:
○ int number = 10;initializes an integer variable named numberwith a value
o 10
f . You can change this value to test other numbers.
4. Check Even or Odd:
○ The program uses an ifstatement to check whetherthe number is even or odd.
○
number % 2 == 0 numberis
: This condition checks if the remainderwhen
2is
divided by 0
. If it is, the number is even.
ifstatement.
○ If the condition is true, it executes the first block of code within the
0), it executes the code in
○ If the condition is false (meaning the remainder is not
the elseblock.
5. Output Result:
○ System.out.println(number + " is even.");prints tothe console that
the number is even.
○ System.out.println(number + " is odd.");prints tothe console that
the number is odd, if the condition was false.
Example Output
number = 10
If you run the program with , the outputwill be:
csharp
Copy code
10 is even.
●
11
If you change the number to :
java
Copy code
int number = 11; // Change to 11
The output will be:
csharp
Copy code
11 is odd.
●
Summary
his program effectively checks whether a predefined number is even or odd without using any
T
numberto test different scenarios. This simple
user input. You can easily modify the value of
structure demonstrates basic conditional logic and arithmetic operations in Java.
4o mini
You said:
with array declaration
ChatGPT said:
ChatGPT
ertainly! Here’s a Java program that checks whether numbers in an array are even or odd.
C
This example will use an array of predefined integers, and we'll iterate through the array to
perform the even-odd check.
Program: Check Even or Odd for Array Elements
java
Copy code
public class EvenOddArray {
public static void main(String[] args) {
// Predefined array of integers
int[] numbers = {10, 21, 34, 45, 60, 73, 88, 99}; // You can
modify these numbers
// Iterate through the array to check each number
for (int number : numbers) {
// Check if the number is even or odd
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
}
Step-by-Step Explanation
1. Class Declaration:
○ public class EvenOddArraydefines a class named
EvenOddArray .
2. Main Method:
○ public static void main(String[] args)is the entrypoint of the
program.
3. Array Declaration:
○ int[] numbers = {10, 21, 34, 45, 60, 73, 88, 99};initializes an
numberswith a set of integers. You canmodify these values to test
rray named
a
other numbers.
4. Iterate Through the Array:
○ for (int number : numbers)is an enhanced for loopthat iterates through
numbersarray. In each iteration,the current element is
each element in the
s number
tored in the variable .
5. Check Even or Odd:
numberis even or odd.
○ Inside the loop, the program checks whether the current
○
if (number % 2 == 0) number
: This condition checks if the remainder of
2is
divided by 0
. If true, the number is even.
ifstatement; if false, it
○ If true, it executes the code in the first block of the
xecutes the
e elseblock.
6. Output Result:
○ System.out.println(number + " is even.");prints thatthe number is
even if the condition is true.
○ System.out.println(number + " is odd.");prints thatthe number is
odd if the condition is false.
Example Output
When you run the program with the given array, the output will be:
sharp
c
Copy code
10 is even.
21 is odd.
34 is even.
45 is odd.
60 is even.
73 is odd.
88 is even.
99 is odd.
Summary
his program effectively checks each element in a predefined array of integers to determine if
T
they are even or odd. By using an array, you can easily manage and evaluate multiple values in
numbersarray to test different sets of
a concise manner. You can modify the contents of the
integers.
********************
1. Set Up WebDriver and Open a Browser
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class OpenBrowser {
public static void main(String[] args) {
// Set the path for the ChromeDriver
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
// Initialize the ChromeDriver
WebDriver driver = new ChromeDriver();
// Open a website
driver.get("https://www.example.com");
// Close the browser
driver.quit();
}
}
Step-by-Step Explanation:
. Import Statements: Import necessary classes from theSelenium library.
1
chromedriverexecutable using
2. Set WebDriver Path: Specify the path to the
System.setProperty()
.
ChromeDriver
3. Initialize WebDriver: Create a new instance of .
driver.get()to navigate to thespecified URL.
4. Open a Website: Use
driver.quit()to close thebrowser and end the session.
5. Close the Browser: Call
2. Find an Element by ID
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElementByID {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Find an element by ID
driver.findElement(By.id("elementId")).click();
driver.quit();
}
}
Step-by-Step Explanation:
. Initialize WebDriver: Similar to the previous example.
1
2. Navigate to URL: Open the target webpage.
3. Find Element by ID: Use driver.findElement(By.id("elementId"))to locate
an element by its ID and click it.
4. Close the Browser: End the session withdriver.quit()
.
3. Find an Element by Class Name
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElementByClassName {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Find an element by class name
driver.findElement(By.className("className")).click();
driver.quit();
}
}
Step-by-Step Explanation:
. O
1 pen the Browser: Initialize the ChromeDriver.
2. Navigate to URL: Access the webpage.
3. Find Element by Class Name: Use
driver.findElement(By.className("className"))to locateand click an
element by its class name.
4. Close the Browser: Use driver.quit()to terminatethe session.
4. Find an Element by Name
java
Copy code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElementByName {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Find an element by name
driver.findElement(By.name("elementName")).sendKeys("Text to
enter");
driver.quit();
}
}
Step-by-Step Explanation:
. O
1 pen the Browser: Initialize the ChromeDriver.
2. Navigate to URL: Access the specified webpage.
3. F ind Element by Name: Use driver.findElement(By.name("elementName"))
to locate an element by its name and enter text.
4. Close the Browser: Terminate the session with driver.quit()
.
5. Get Page Title
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetPageTitle {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Get the title of the page
String title = driver.getTitle();
System.out.println("Page title is: " + title);
driver.quit();
}
}
Step-by-Step Explanation:
.
1 pen the Browser: Initialize the ChromeDriver.
O
2. Navigate to URL: Open the webpage.
3. Get Page Title: Call driver.getTitle()to retrievethe page title.
4. Print Title: Output the title to the console.
5. Close the Browser: Use driver.quit()to end the session.
6. Get Current URL
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetCurrentURL {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Get the current URL
String currentUrl = driver.getCurrentUrl();
System.out.println("Current URL is: " + currentUrl);
driver.quit();
}
}
Step-by-Step Explanation:
.
1 pen the Browser: Initialize the ChromeDriver.
O
2. Navigate to URL: Open the webpage.
3. Get Current URL: Call driver.getCurrentUrl()to retrievethe URL.
4. Print URL: Output the current URL to the console.
5. driver.quit()
Close the Browser: End the session with .
7. Navigate Back and Forward
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class NavigateBackAndForward {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Navigate to another page
driver.navigate().to("https://www.google.com");
// Navigate back to the previous page
driver.navigate().back();
// Navigate forward to the next page
driver.navigate().forward();
driver.quit();
}
}
Step-by-Step Explanation:
. O
1 pen the Browser: Initialize the ChromeDriver.
2. Navigate to Initial URL: Open the first webpage.
3. Navigate to Another Page: Use driver.navigate().to()to visit a new URL.
driver.navigate().back()to return tothe previous page.
4. Go Back: Call
driver.navigate().forward()to moveforward.
5. Go Forward: Call
driver.quit()to end the session.
6. Close the Browser: Use
8. Refresh the Page
java
Copy code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class RefreshPage {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Refresh the page
driver.navigate().refresh();
driver.quit();
}
}
Step-by-Step Explanation:
. O
1 pen the Browser: Initialize the ChromeDriver.
2. Navigate to URL: Open the target webpage.
3. Refresh the Page: Use driver.navigate().refresh()to reload the current page.
driver.quit()
4. Close the Browser: End the session with .
9. Handle Alerts
java
Copy code
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandleAlerts {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Assume an alert pops up here
Alert alert = driver.switchTo().alert();
System.out.println("Alert message: " + alert.getText());
alert.accept(); // Clicks OK on the alert
driver.quit();
}
}
Step-by-Step Explanation:
. O
1 pen the Browser: Initialize the ChromeDriver.
2. Navigate to URL: Open the webpage.
driver.switchTo().alert()tofocus on the alert.
3. Switch to Alert: Use
alert.getText()
4. Get Alert Text: Retrieve the alert message with .
alert.accept()
5. Accept Alert: Click the OK button using .
driver.quit()to end the session.
6. Close the Browser: Use
10. Take a Screenshot
java
Copy code
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class TakeScreenshot {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Take a screenshot
File screenshot = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
driver.quit();
}
}
Step-by-Step Explanation:
. O
1 pen the Browser: Initialize the ChromeDriver.
2. Navigate to URL: Open the specified webpage.
3. Take a Screenshot: Use ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE)to capturethe screenshot.
FileUtils.copyFile()to savethe screenshot.
4. Save the Screenshot: Use
driver.quit()
5. Close the Browser: Terminate the session with .