Selenium With Java - Day1
Selenium With Java - Day1
📘 Introduction to Selenium
🔹 What is Selenium?
● Selenium is an open-source automation testing tool used for testing web applications.
● It allows automation of browser actions (clicks, typing, navigation, validations, etc.).
● It supports multiple programming languages (Java, Python, C#, Ruby, JavaScript).
● Works across different browsers (Chrome, Firefox, Edge, Safari) and operating
systems.
🔹 Components of Selenium
1. Selenium IDE – Record & playback tool (basic, not used much in real projects).
2. Selenium RC (deprecated) – Older version, replaced by WebDriver.
3. Selenium WebDriver – Core part of Selenium, used to interact directly with browsers.
4. Selenium Grid – Used for parallel execution across multiple machines/browsers.
🔹 What is WebDriver?
● WebDriver is a browser automation API.
● It sends commands to the browser and retrieves results.
● It uses browser-specific drivers (e.g., ChromeDriver, GeckoDriver).
● Unlike Selenium IDE, WebDriver interacts with the browser like a real user.
🔹 What is a Driver?
● A driver is a bridge between Selenium WebDriver and the browser.
● Each browser needs its own driver:
○ Chrome → chromedriver.exe
○ Firefox → geckodriver.exe
○ Edge → msedgedriver.exe
● The driver translates Selenium code into browser-specific commands.
👉 This helps students see Selenium as the de facto standard for browser automation.
👉 This avoids the misconception that Selenium is a “one-stop” tool for all testing.
🔹 Selenium Ecosystem
Explain that Selenium is not just WebDriver:
● Selenium IDE – A browser plugin for recording & playback (good for beginners).
● Selenium RC (Deprecated) – Old tool replaced by WebDriver.
● Selenium WebDriver – Core API for automating browsers (most widely used).
● Selenium Grid – Used for parallel execution across multiple machines/browsers.
👉 Students will then know that WebDriver is a part of Selenium, not Selenium itself.
👉 Students will appreciate Selenium better if they know where it shines and where it
struggles.
// Open website
driver.get("https://www.google.com");
// Close browser
driver.quit();
}
}
🔹 Key Notes
● Always match driver version with your browser version.
● Selenium works only for web applications (not desktop or mobile directly).
● For advanced automation, Selenium can be integrated with:
○ TestNG / JUnit (for test management)
○ Maven / Gradle (for dependency management)
○ Jenkins (for CI/CD automation)
Locators in Selenium
🔹 Introduction
● We can identify various elements in a webpage using locators.
● Locator: An address that uniquely identifies a web element within a page.
● Types of locators can be defined as:
○ Directly found in DOM
○ Customized locators (when not directly found)
🔹 Types of Locators
1. ID
2. Name
3. LinkText
4. PartialLinkText
5. ClassName
6. TagName
7. CSS Selector
○ Tag and ID
○ Tag and class
○ Tag and attribute
○ Tag, class, and attribute
8. XPath
○ Absolute XPath
○ Relative XPath
🔹 Locator Notes
● Sometimes, we may use a locator and it might not work, maybe because the attribute of
the locator keeps on changing.
● In such cases, we can use XPath or CSS Selector to locate elements.
● Hence, Selenium provides multiple locator options.
🔹 Finding Elements
● We can search for a locator of any element by moving on a webpage and inspecting its
elements.
● To locate an element using locators, we use:
driver.findElement(By.id("value"))
🔹 findElement
● Used when we want to interact with a single web element.
● Return type of findElement → a single WebElement.
1. ID Locator
● ID is the fastest locator to search for an element.
● Each element has a unique ID attribute (if available).
● Syntax to interact with any element using ID locator:
driver.findElement(By.id("value"));
2. Name Locator
● Uses the name attribute value of any element to interact with it.
● Syntax to interact with any element using Name locator:
driver.findElement(By.name("value"));
3. LinkText Locator
● Used to locate links on a webpage.
● Works only for <a> (anchor) tag.
● Example:
<a href="www.approach.com">Tablet</a>
● Points:
○ LinkText is available only for links (<a> tag).
○ LinkText matches the visible text inside the link.
○ If <a> has inner text, it is LinkText, else it is innerText.
● Syntax:
driver.findElement(By.linkText("Tablet")).click();
driver.findElement(By.linkText("textValue")).click();
Syntax:
driver.findElement(By.partialLinkText("value"));
Example:
driver.findElement(By.partialLinkText("Tab"));
Notes:
● Partial LinkText is not preferred because partial values may locate some
different/incorrect elements as well.
● It is preferred only when there is something common in 2 or more link texts.
5. TagName Locator
● TagName and ClassName locators are used when we want to locate a group of
elements.
● They are not preferred for locating a single element.
● TagName is used when we want to locate all elements of a specific tag, like:
○ <input>
○ <button>
○ <img>
○ <a>, etc.
Syntax:
driver.findElement(By.tagName("value"));
Example:
6. ClassName Locator
● ClassName = a category of elements.
● The class attribute is mainly used for:
○ Buttons
○ Checkboxes
○ Radio buttons
○ Dropdowns, etc.
● Same category of elements share the same class attribute.
● Hence, ClassName is used when we want to get a group of web elements.
Syntax:
driver.findElements(By.className("value"));
List<WebElement> elements =
driver.findElements(By.className("value"));
Important:
🔹 Assignments
1. Go to http://www.demo1sage.com/links.html
(i) Find total number of links.
(ii) Find total number of images.
(iii) Click on any product link using LinkText / PartialLinkText.
🔹 Question: If we already have ID and Class, why do we need CSS selectors with other
👉
locators?
Because for complex webpages, locating elements with a single locator might not be
possible. Hence, we need to combine it with more than one tag/attribute.
Syntax: driver.findElement(By.cssSelector("tagname#id"));
Syntax: driver.findElement(By.cssSelector("tagname.classname"));
driver.findElement(By.cssSelector("tagname[attribute='value']"));
📌 Assignment
1. Go to: “demowebsite.com”
2. Try to work out all types of locators to identify elements by using all the combinations.
⭐ XPath Locator:
● XPath Locator is the most important locator and is preferred to use.
● 80–90% of the time it is used to locate elements due to its accuracy.
● XPath is derived from XML Path.
● XPath is an address of an element.
● XPath can be captured from the DOM (HTML).
● DOM = Document Object Model → generated at runtime when we write a webpage.
👉 XPath for an element will only be captured when the DOM is fully loaded. If the DOM is not
loaded, we cannot find the element with correct XPath.
Types of XPath:
1. Absolute XPath (Full XPath)
2. Relative XPath (Partial XPath)
We can capture the XPath of any element directly from the webpage by right-clicking the
element and copying Full XPath / Relative XPath.
Absolute XPath:
Example: /html/body/header/div/div/div[2]/div/input
Relative XPath:
Example: //*[@name='search']
⭐ More Details
● Most of the time Relative XPath is preferred because:
1. The developer might add/remove elements between nodes → this will break
Absolute XPath.
2. Relative XPath does not traverse the full DOM, it directly identifies elements
using attributes.
3. Absolute XPath makes code lengthy & unreadable, while Relative XPath is
short and clean.
Example: /html/body/header/div/div/div[2]/div/input
Example: //input[@name='search'][@placeholder='Search']
Using OR Operator:
//tagname[@attribute1='value1' or @attribute2='value2']
Example: //a[text()='Desktop']
1. The contains() method is like text() but it allows partial matches of attribute values.
Syntax: //tagname[contains(@attribute,'partialValue')]
Example: //input[contains(@placeholder,'Sea')]
1. Similar to contains() but checks only the starting value of attribute.
Syntax: //tagname[starts-with(@attribute,'startingValue')]
Example: //input[starts-with(@placeholder,'sea')]
Dynamic Elements
● Dynamic elements are those whose attribute values change after some actions (page
refresh, loading, re-rendering, etc).
● To handle them, we use contains() and starts-with() methods.
Scenario 2
👉 Approach:
//name[contains(@name,'xyz001')]
Scenario 3
👉 Approach:
//name[contains(@name,'xyz')]
Scenario 4
👉 Approach:
//name[contains(@name,'01')]
Chained XPath
(i) Scenario:
When we do not have any attribute or inner text for an element, we use Chained XPath.
(ii) Explanation:
● Relative XPath comes into picture when the element we want to interact with has no
attribute or inner text.
● Then, we move to its parent node.
● If the parent also doesn’t have any attribute or text, we move further up until we find an
element with attribute/text.
Example: //img[@id='logo']/../img
Here:
XPath Axes
Node Tree Structure
● 6 is the focus node.
● 7, 9, 10 are the child nodes of node 6.
● 1, 4 are the ancestor nodes of node 6.
● 2, 3 are the following-siblings of node 6.
● 5 is the preceding-sibling of node 6.
● 8 is the descendant of node 7.
Key Points
1) self:
● Current node is the self node.
● Syntax: //tagname[@attribute='value']/self::tagname
● Example: //a[contains(text(),'India Tourism De')]/self::a
2) child:
3) parent:
4) Following
● Parallel node on the right side of the parent node is following node.
● Traverses all the elements that come after the current tag.
Syntax:
//tag[@attribute='value']/following::tagname
Example:
5) Preceding
● Parallel node on the left side of the parent node is preceding node.
● Traverses all the elements that come before the current tag.
Syntax:
//tag[@attribute='value']/preceding::tagname
Example:
6) Following-sibling
● Parallel node on the right side of the self node is following-sibling node.
● Traverses from current HTML tag to next sibling HTML tag.
Syntax:
//tagname[@attribute='value']/following-sibling::siblingtag[@attribute
='value']
Example:
7) Preceding-sibling
● Parallel node on the left side of the self node is preceding-sibling node.
● Traverses from current HTML tag to previous sibling HTML tag.
Syntax:
//tagname[@attribute='value']/preceding-sibling::previous-siblingtag[@
attribute='value']
Example:
8) Ancestor
● Parent of parent node is the ancestor node.
● Traverses all the ancestor elements (grandparent, parent, etc.) of the current HTML
tag.
Syntax:
//tagname[@attribute='value']/ancestor::tagname
Examples:
2. If there is no descendant of self, then it can go to ancestor and then go to its child:
9) Descendant
● Child of the child node is the descendant node.
● Traverses all the descendant elements (child → grandchild → etc.) of the current
HTML tag.
Syntax:
//tagname[@attribute='value']/descendant::tagname
Examples:
2. If there is no descendant of self, then it can go to ancestor and then go to its
descendant:
WebDriver Methods
WebElement
● WebElement is an element on the webpage.
● It can be a checkbox, textbox, dropdown, button, etc.
● Whatever we see on the webpage is implemented as a WebElement.
Get Methods
Get methods work on web pages. We can access get methods through WebDriver instance.
driver.get("url");
1. Conditional Methods
Conditional methods work on WebElements.
We can access these commands through WebElement.
These methods return a boolean value (true/false).
(i) isDisplayed()
(ii) isEnabled()
(iii) isSelected()
✅ Common Syntax
driver.findElement(By.locator("value")).isDisplayed();
driver.findElement(By.locator("value")).isEnabled();
driver.findElement(By.locator("value")).isSelected();
2. Browser Methods
Browser methods work on the browser window.
We can access them through the WebDriver instance.
(i) close()
driver.close();
(ii) quit()
driver.quit();
⚠️ Problem:
● If WebElement is not available, script execution fails.
● Wait commands help handle such issues.
(A) Thread.sleep(milliseconds)
✅ Advantages
1. Very easy to use.
❌ Disadvantages
1. If wait time is insufficient → Exception will occur.
2. Always waits for the maximum time → reduces script performance.
○ Example: Thread.sleep(3000) waits full 3 sec, even if element loads in 1
sec.
3. Needs to be written multiple times for multiple waits.
1. Implicit Wait
✅ Syntax
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
(Default = 0 seconds)
✅ Key Points
● Written only once in the script.
● Waits for the element until the max time is reached.
● If element found earlier, execution continues immediately.
Advantages
Disadvantages
✅ Steps
1. Declaration of wait
2. Usage with conditions
✅ Syntax
WebDriverWait mywait = new WebDriverWait(driver,
Duration.ofSeconds(10));
WebElement element =
mywait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/
/input[@placeholder='username']")));
element.sendKeys("Anakat01");
📌 Key Points
● Waits until condition is satisfied OR max time is reached.
● Mostly used for elements facing synchronization problems.
● alertIsPresent()
● elementToBeClickable()
● elementToBeSelected()
● frameToBeAvailableAndSwitchToIt()
● presenceOfElementLocated()
● textToBePresentInElementLocated()
● titleContains()
● urlContains()
● visibilityOf()
● visibilityOfAllElements()
● visibilityOfElementLocated() ✅ (most used)
✅ Advantages of Explicit Wait
1. Condition-based → handles waits more effectively.
2. Finding elements is inclusive (for some conditions).
3. Will wait for the condition to be true until the timeout.
5. Fluent Wait
● Works similar to Explicit Wait but gives more control (polling frequency, ignoring
exceptions, etc.).
● Must first declare and then use it.
✅ Declaration
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(10)) // max wait time
.pollingEvery(Duration.ofSeconds(2)) // polling interval
.ignoring(NoSuchElementException.class); // ignore exception
✅ Usage
WebElement elementname = wait.until(new Function<WebDriver,
WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.xpath("locator"));
}
});
6. Navigation Commands
There are 4 navigation commands in Selenium WebDriver:
✅ Syntax
driver.navigate().to("https://example.com");
✅ Commands
1. driver.getWindowHandles() → Returns all window IDs (Set of Strings).
2. driver.switchTo().window(windowID) → Switch to desired window.
✅ Approach
Step 1: Open webpage → click link → new window opens.
Step 2: Get all window IDs → driver.getWindowHandles().
Step 3: Convert Set → List (for easy access).
Step 4: Store Parent & Child window IDs.
Step 5: Switch using driver.switchTo().window(childID).
Step 6: Perform operations on child window.
Step 7: Close child window using driver.close().
Step 8: Switch back to parent using driver.switchTo().window(parentID).
✅ Example Code
public class WindowHandleExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://opensource-demo.orangehrmlive.com/");
driver.findElement(By.xpath("//a[contains(text(),'OrangeHRM')]")).clic
k();
Checkbox Operations
(1) Selecting a Single Checkbo
Syntax:
driver.findElement(By.locator("locatorValue")).click();
Syntax:
List<WebElement> varname =
driver.findElements(By.locator("locatorValue"));
for (int i = 0; i < varname.size(); i++) {
varname.get(i).click();
}
Or:
Syntax:
Example:
● Total checkboxes = 7
● Need to select last 3 → start index = 7 - 3 = 4
Syntax:
Syntax:
1.Normal Alert
2.Confirmation Alert
3.Prompt Alert
● Until we close/perform some action on alerts, no operation can be performed on the
webpage.
● Alerts are not WebElements, hence cannot be inspected.
(1) Normal Alert
● To perform actions, switch to alert window.
driver.switchTo().alert();
Syntax 1 (direct):
driver.switchTo().alert().accept();
To click OK:
driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
Steps:
Or:
● Alerts can be handled with switchTo(), but also with Explicit Wait.
Authenticated Pop-ups
1. These types of popups are rare to find.
2. Authentication popups will not allow entering into a website unless the username and
password are provided.
3. We cannot use switchTo() or command or explicit wait to handle this type of popup.
4. The only option to handle such type of popup is by using the injection method.
○ In the injection method, we simply pass the username and password with the
URL of the webpage.
○ Example (without injection):
https://the-internet.herokuapp.com/basic_auth
Example:
https://admin:[email protected]/basic_auth
5. When we inject the username and password in the URL, we do not get the
authentication popup.
1. driver.switchTo().frame(name)
2. driver.switchTo().frame(id)
3. driver.switchTo().frame(WebElement)
4. driver.switchTo().frame(frameIndex) → Preferred only when there is a single
frame
Once we enter a frame and interact with it, we need to come out of it to work on the webpage
again.
driver.switchTo().defaultContent();
Multiple Frames
If a webpage has multiple frames, we must enter one frame, exit it, then enter another frame,
and so on.
Example:
enter frame1
exit frame1
enter frame2
exit frame2
Nested Frames
Example:
enter frame1
enter frame2
enter frame3
exit frame3
exit frame2
exit frame1
Switching Methods
There are 3 types of switching methods:
1. Browser Windows: driver.switchTo().window(windowID/windowHandle);
2. Alerts:
driver.switchTo().alert();
driver.switchTo().accept();
driver.switchTo().dismiss();
3. Frames
driver.switchTo().frame(id);
driver.switchTo().frame(name);
driver.switchTo().frame(WebElement);
1. Select Dropdown
● A dropdown can only be considered a Select dropdown if it is inside the <select> tag.
● Select dropdowns are easy to handle as there are built-in methods.
● Not used much these days compared to other dropdowns.
● The dropdown itself is a web element containing multiple <option> elements.
● We usually perform only one action → selecting an option from the dropdown.
Steps:
Example:
3. Bootstrap Dropdowns
● Dropdowns having tags other than <select> are called Bootstrap or Hidden
Dropdowns.
● Some dropdowns allow multiple selection (like checkboxes).
● In Bootstrap/hidden dropdowns, XPath is the most reliable way to locate elements.
● ⚠️
● Captures and clicks/expands the dropdown.
Value should be common & stable (not dynamically changing with page reloads).
Assignment
1. Handle Training Dropdowns with/without Select Class
https://phptravels.com/demo/jquery-dependent-dropdown-list-countr
ies-and-states/
○ (a) Count total number of options
○ (b) Print all options
○ (c) Select one option
2. Hidden Dropdown
○ Login to OrangeHRM → PIM → Employee Status
🔗
3. Custom Multi-Select Box
http://testautomationpractice.blogspot.com/
(4) Auto-Suggest Dropdowns
● An example of auto-suggest dropdown is the Google Search bar.
● Auto-suggest dropdown is a dynamic dropdown but the options keep on changing.
● To handle auto-suggest dropdowns:
Step 1: Visit the page, capture the dropdown and search for some value using a unique XPath
or locator.
Step 2: Wait for 5 seconds as it takes some time to suggest the options.
Step 3: Write an XPath that matches all the elements (including the options).
List<WebElement> list =
driver.findElements(By.xpath("//ul[@role='listbox']//li/descendant::di
v[@class='wM6W7d']"));
Perform Action
● After this, simply perform whatever action we want.
● Once clicking on an option, we should break the loop as we do not need other options.
if (list.get(i).getText().equals("Selenium")) {
list.get(i).click();
break;
}
}
Web Tables
Types of Web Tables
1. Static Web Table
○ Fixed rows & columns
2. Dynamic Web Table
○ Fixed columns, rows can change
3. Web Table with Pagination
○ Table is distributed across multiple pages due to large no. of records
JS Mukesh JS 200
Important Notes
● The order can be different depending on table to table.
● Different operations can be performed on a table.
● This can be done by simply counting the <tr> tags in the table.
Syntax: driver.findElements(By.xpath("locator_value")).size();
Example:
driver.findElements(By.xpath("//table[@name='BookTable']//tr")).size()
;
or
driver.findElements(By.tagName("tr")).size();
● This can be found by counting the number of <th> or <td> tags in the table.
Syntax:
driver.findElements(By.xpath("value")).size();
or
driver.findElements(By.tagName("td")).size();
● This can be achieved by writing that particular <tr> tag and <td> tag in the table.
Syntax:
driver.findElement(By.xpath("value")).getText();
👉 Example:
// When text or string is stored at some location
// xpath expression example:
"//table[@name='BookTable']/tbody/tr[3]/td[1]"
Syntax:
🔑 Note:
● i = 2 because tr[1] holds headers (<th>).
● If no headers are present, loop can start from i = 1.
● When we want to pass values from a string or row/col dynamically, we must append
using + operator.
if (authorName.equals("Mukesh")) {
String bookName = driver.findElement(
By.xpath("//table[@name='BookTable']/tbody/tr[" + i +
"]/td[1]")
).getText(); // 1st column contains book names
System.out.println(bookName);
}
}
(vii) Extract all the prices and calculate the total price
This can be done in 3 steps:
Code Example:
int total = 0;
for (int i = 2; i <= rows; i++) {
String price = driver.findElement(
By.xpath("//table[@name='BookTable']/tbody/tr[" + i +
"]/td[3]")
).getText(); // 3rd column holds prices
(i) How to count total number of pages in dynamic webtable with pagination
(Other method is counting total number of tags in which each page is present).
Here, we can get the total pages (i.e. 1909) by simply using substring method:
substring(26, 30); // 1909
⚠️ Problem:
Since the table is dynamic, values and data will change and hence page numbers can
sometimes be 4 digits, sometimes 3, 2, or 1.
Here, the hardcoded index will change and script will fail.
✅ Solution:
To overcome this, we need to find something static, something that remains in the string
consistently and use them.
Example:
Output string:
"1909 Pages"
● Here we can use their index:
○ index of "(" = 1st index of number.
○ index of "Pages" = last index of number.
Since page number extracted is a string (substring from the captured text), we need to
convert it to an integer using
Integer.parseInt(...).
if (p > 1) {
// Since page 1 is by default visible,
// consider if page is greater than 1
WebElement activePage = driver.findElement(
By.xpath("//ul[@class='pagination']//a[text()='" + p +
"']")
);
activePage.click();
}
}
Extracting Data from Each Page (Example: Customer Name in 2nd Column)
To extract data (e.g., Customer Name which is in the 2nd column) from all rows of a table:
ASSIGNMENT
● Go to: "testautomationpractice.blogspot.com"
● Do the dynamic webtable:
1. Count total pages.
2. Visit each page.
3. Read data from each page.
4. Click on checkbox as per certain condition.
📅 Date Pickers / Calendars in Automation
🔹 Types of Web Elements
1. Standard Elements
○ Same type across almost every website.
○ Easy to automate as their structure is consistent.
2. Non-Standard / Customized Elements
○ Differ across websites depending on how developers design them.
○ Automation is harder since there’s no fixed structure.
○ Date Pickers / Calendars usually fall under this category.
🔹 General Observations
● Sometimes, simply using the sendKeys() command works for inputting dates.
● On other pages, you may need to automate switching between day, month, and year.
● If dropdowns are present, automation is easier as you can just click/select values.
⚠️ Note: If sendKeys() doesn’t work, you must handle it with custom logic (e.g., selecting
from the UI).
Steps:
Step 1: Click on the date picker field.
Step 2: Capture the displayed month and year values into variables and then compare them
with your expected date and year.
Step 3: Keep on comparing the month and year with input month and year until we find our
match.
Step 4: Once match is found, simply select the date and done.
Step 5: We will have to keep on clicking until expected month and year is not found because we
do not know how many end condition will come.
Step 6: Since ending condition is not known, hence we will use WHILE LOOP in this case.
Logic / Pseudocode:
boolean x = true;
while(x == true) {
At_month = driver.findElement(By.xpath("value")).getText();
At_year = driver.findElement(By.xpath("value")).getText();
date =
driver.findElement(By.xpath("//a[contains(@class,'ui-state-default')][
text()='7']")).click();
for(WebElement d : alldates) {
if(d.getText().equals("12")) { // if
(d.getText().equals(date))
d.click();
break;
}
}
}
● Using this class and its methods, we can perform mouse operations like:
○ Mouse hover
○ Left click
○ Right click
○ Double click
○ Drag & Drop
Actions Class
● The Actions class contains multiple methods for handling advanced user interactions.
● To use it, we need to:
✅ Syntax:
act.moveToElement(driver.findElement(By.xpath("elementLocator"))).perf
orm();
➡️ This performs hover on Desktop → then hover on Mac → then click on Mac.
2. Right Click Action → contextClick(element)
To perform a Right Click on an element:
Steps:
1. Capture the element.
2. Create an Actions class object.
3. Use contextClick(element) method.
✅ Example:
WebElement button = driver.findElement(By.xpath("value"));
Actions act = new Actions(driver);
act.contextClick(button).perform();
Steps:
1. Capture the element.
2. Create an Actions class object.
3. Use doubleClick(element) method.
✅ Example:
WebElement button = driver.findElement(By.xpath("value"));
Actions act = new Actions(driver);
act.doubleClick(button).perform();
4. Drag and Drop → dragAndDrop(sourceElement,
targetElement)
● Drag and Drop is possible only if the application supports it.
Steps:
1. Capture the source and target elements.
2. Create an Actions class object.
3. Use dragAndDrop(source, target) method.
✅ Example:
WebElement source = driver.findElement(By.xpath("value1"));
WebElement target = driver.findElement(By.xpath("value2"));
act.dragAndDrop(source, target).perform();
○ Select All
○ Copy–Paste
○ Enter
○ Tab
○ Backspace
○ etc.
// Copy → Ctrl + C
act.keyDown(Keys.CONTROL)
.sendKeys("c")
.keyUp(Keys.CONTROL)
.perform();
✅ Similarly, we can handle other keys like Enter, Tab, Esc, etc.
Example:
driver.findElement(By.xpath("//input[@type='file']"))
.sendKeys("C:\\path\\to\\file1.txt");
Syntax:
driver.findElement(By.xpath("//input[@type='file']"))
.sendKeys(file1 + "\n" + file2 + "\n" + file3);
Important Notes
● A single variable can hold only one screenshot.
For multiple screenshots, multiple variables must be used.
● The temporary location of the screenshot is unknown.
We must copy it to a target file for saving.
● To save the screenshot, we use File class.
srcFile.renameTo(targetFile);
// Capture screenshot
TakesScreenshot ts = (TakesScreenshot) driver;
File srcFile = ts.getScreenshotAs(OutputType.FILE);