100 Java Selenium Coding Questions
100 Java Selenium Coding Questions
// Using StringBuilder
String reversed = new
StringBuilder(original).reverse().toString();
System.out.println("Reversed: " + reversed);
}
}
Reversed: noitamotua
by Sreenidhi Rajakrishnan
Palindrome Checker
Problem
Check if the given string reads the same backward as forward.
Technique
Compare original string with its reverse.
Time Complexity
O(n) where n is the string length.
Output:
by Sreenidhi Rajakrishnan
Swap Two Numbers
Output:
by Sreenidhi Rajakrishnan
Finding the Largest Number
Initialize
Set first element as the largest number.
Compare
Loop through array and update max if larger number found.
Return
Output the maximum value after full traversal.
Output:
Largest number: 25
by Sreenidhi Rajakrishnan
Finding the Smallest Number
1
2
4
3
1 Initialize
Set first element as smallest.
2 Compare
Loop through array comparing values.
3 Update
Replace min if smaller found.
4 Output
Return the minimum value.
Output:
Smallest number: 3
by Sreenidhi Rajakrishnan
Counting Vowels and
Consonants
Input Process
Take a string input to analyze. Check each character for vowel or
consonant.
Count
Maintain separate counters for each
type.
Output:
Vowels: 6, Consonants: 10
by Sreenidhi Rajakrishnan
Character Occurrence
Counter
HashMap Approach
Use HashMap to store each character and its count.
Time Complexity
O(n) where n is string length.
Application
Useful for text analysis and data processing.
import java.util.HashMap;
System.out.println(charCount);
}
}
Output:
by Sreenidhi Rajakrishnan
Fibonacci Series
Initialize
1
Start with 0 and 1.
Calculate
2
Next number is sum of previous two.
Print
3
Output each Fibonacci number.
Continue
4
Repeat until reaching desired count.
Output:
1 1 2 3 5 8 13 21 34 55
by Sreenidhi Rajakrishnan
Factorial Calculation
Loop Method
1
Use iteration to multiply numbers.
Recursive Method
2
Function calls itself with decremented value.
Base Case
3
Factorial of 0 or 1 is 1.
// Loop method
int factorial1 = 1;
for (int i = 1; i <= num; i++) {
factorial1 *= i;
}
// Recursive method
int factorial2 = factorialRecursive(num);
Output:
by Sreenidhi Rajakrishnan
Prime Number Check
2
First Prime
Only even prime number.
:n
Check Limit
Only need to check divisors up to square root.
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
Output:
17 is prime: true
by Sreenidhi Rajakrishnan
Sum of Digits
Extract Remove
Get last digit using Remove last digit by
modulo. dividing.
1 2 3 4
Add Repeat
Add digit to running sum. Continue until no digits
remain.
Output:
Sum of digits: 15
by Sreenidhi Rajakrishnan
Remove Duplicates from
Array
Set Collection
Automatically removes duplicates
ArrayList
Stores unique elements
Original Array
May contain duplicates
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
// Using HashSet
Set<Integer> uniqueSet = new HashSet<>(Arrays.asList(numbers));
Integer[] uniqueNumbers = uniqueSet.toArray(new Integer[0]);
Output:
Original: [1, 2, 3, 2, 5, 1, 6, 3, 7]
Without duplicates: [1, 2, 3, 5, 6, 7]
by Sreenidhi Rajakrishnan
Reverse Words in String
Output:
by Sreenidhi Rajakrishnan
Find Even and Odd Numbers
Input Array [1, 2, 3, 4, 5, 6, 7, 8, 9]
import java.util.ArrayList;
Output:
by Sreenidhi Rajakrishnan
String Length Without
.length()
Char Array Method
1
Convert string to character array and count elements.
Index Method
2
Use exception handling to count characters until the end.
Manual Count
3
Iterate through indices until StringIndexOutOfBoundsException.
try {
while (true) {
str.charAt(length);
length++;
}
} catch (StringIndexOutOfBoundsException e) {
// End of string reached
}
Output:
Length of string: 10
by Sreenidhi Rajakrishnan
String to Integer Conversion
String to Integer Integer to String
// Integer to String
int number = 12345;
String str = Integer.toString(number);
System.out.println("Integer to String: " + str);
}
}
Output:
by Sreenidhi Rajakrishnan
Print Elements at Even/Odd
Indexes
1 2 3 4
Output:
by Sreenidhi Rajakrishnan
Array Reversal
Reverse Elements
To reverse the array, create a new array and iterate from the end of the original
array to the beginning, assigning elements to the new array in reverse order.
import java.util.Arrays;
int start = 0;
int end = array.length - 1;
// Move pointers
start++;
end--;
}
Output:
Original: [1, 2, 3, 4, 5]
Reversed: [5, 4, 3, 2, 1]
by Sreenidhi Rajakrishnan
Check if Array is Sorted
To check if an array is sorted, loop through the array and compare each element
with the next one in sequence. If any element is greater than the next, return false
indicating the array is not sorted. Otherwise, return true if the loop completes
without finding any unsorted pairs.
Output:
by Sreenidhi Rajakrishnan
Case Conversion
Using String Methods Manual Character
Conversion
String str = "Hello";
String upper =
// ASCII value difference: 32
str.toUpperCase();
// 'A' (65) to 'a' (97)
String lower = str.toLowerCase();
char upper = 'a';
char lower = (char)(upper - 32);
Output:
by Sreenidhi Rajakrishnan
Find Second Largest Number
in an Array
Sort array
One approach is to sort and find second-to-last element
Implement solution
Use a loop that tracks largest and second largest
Output
by Sreenidhi Rajakrishnan
Find Duplicate Elements in
an Array
Hash Set
Use HashSet to track seen elements
Single Pass
Process array elements just once
Store Duplicates
Add duplicates to result list
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
Output
by Sreenidhi Rajakrishnan
Check if Two Strings are
Anagrams
What are anagrams? Solution approaches
Two strings containing same 1. Sort both strings and compare
characters with same frequency but 2. Count character frequencies
different order.
3. Use character array for counting
Examples: "listen" and "silent",
"triangle" and "integral"
Output
by Sreenidhi Rajakrishnan
Find the Missing Number in a
Sequence
1
Start
Begin with sequence 1 to N
N
End
Expected to have all numbers
N-1
Given
Array contains all except one number
?
Find
Identify the missing number
Output
Missing number: 5
by Sreenidhi Rajakrishnan
Sort an Array Without Using
Arrays.sort()
Choose a Sorting Algorithm
We'll implement Bubble Sort as a simple example.
Output
by Sreenidhi Rajakrishnan
Find the First Non-Repeated
Character in a String
Character Frequency Map
Use HashMap to track character counts in the string.
Two-Pass Approach
First count occurrences. Then find first character with count of 1.
Time Complexity
O(n) where n is the length of the string.
import java.util.HashMap;
import java.util.Map;
if (result != '\0') {
System.out.println("First non-repeated character: " + result);
} else {
System.out.println("No non-repeated character found");
}
}
}
Output
by Sreenidhi Rajakrishnan
Find Common Elements in
Two Arrays
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
Output
by Sreenidhi Rajakrishnan
Count Frequency of
Elements Using HashMap
4.5
1.5
0
Apple Banana Orange Grape
import java.util.HashMap;
import java.util.Map;
return frequencyMap;
}
System.out.println("Frequency of elements:");
for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Output
Frequency of elements:
Apple: 3
Grape: 1
Orange: 4
Banana: 2
by Sreenidhi Rajakrishnan
Reverse Words in a Sentence
Split sentence into words
Use string split method
return reversed.toString();
}
Output
by Sreenidhi Rajakrishnan
Find Pairs in Array Whose
Sum Equals a Target
Define Problem
Find all pairs (a,b) where a+b equals target sum
Check Complement
For each number, look for (target-number)
Collect Pairs
Add matching pairs to result list
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
if (visitedNumbers.contains(complement)) {
pairs.add(new int[]{complement, num});
}
visitedNumbers.add(num);
}
return pairs;
}
Output
by Sreenidhi Rajakrishnan
Merge Two Sorted Arrays
Start with two sorted arrays
Arrays are already in order
int i = 0, j = 0, k = 0;
// Compare elements from both arrays and add smaller one to result
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
return result;
}
Output
by Sreenidhi Rajakrishnan
Convert a List to Set and Vice
Versa
List to Set Conversion
Pass List to Set constructor to remove duplicates
Use Cases
Remove duplicates or restore original order
Key Differences
List allows duplicates and maintains order; Set has unique elements
import java.util.*;
Output
by Sreenidhi Rajakrishnan
Use of ArrayList, HashSet,
and HashMap in Code
import java.util.*;
// HashSet demo
HashSet<String> uniqueFruits = new HashSet<>();
uniqueFruits.add("Apple");
uniqueFruits.add("Banana");
uniqueFruits.add("Apple"); // Duplicate not added
System.out.println("HashSet: " + uniqueFruits);
// HashMap demo
HashMap<String, Integer> fruitCounts = new HashMap<>();
fruitCounts.put("Apple", 5);
fruitCounts.put("Banana", 3);
fruitCounts.put("Orange", 2);
System.out.println("HashMap: " + fruitCounts);
System.out.println("Apple count: " + fruitCounts.get("Apple"));
}
}
Output
by Sreenidhi Rajakrishnan
Remove All White Spaces
from a String
Input Output
return result.toString();
}
Output
by Sreenidhi Rajakrishnan
Extract Only Digits from an
Alphanumeric String
Extract Digits
Filter out all non-digit characters
Validate Solutions
Test with various alphanumeric
inputs
return result.toString();
}
Output
by Sreenidhi Rajakrishnan
Read Data from Excel Using
Apache POI
Dependencies Core Classes
Add Apache POI libraries to your XSSFWorkbook: For XLSX files
project. HSSFWorkbook: For XLS files
poi-5.2.3.jar Sheet, Row, Cell: For data access
poi-ooxml-5.2.3.jar
commons-io-2.11.0.jar
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
file.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
by Sreenidhi Rajakrishnan
Capture a Screenshot in
Selenium Using Java
Set up WebDriver instance
Initialize and configure Chrome/Firefox driver
import java.io.File;
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;
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
try {
// Navigate to website
driver.get("https://www.example.com");
// Take screenshot
TakesScreenshot scrShot = (TakesScreenshot) driver;
File srcFile = scrShot.getScreenshotAs(OutputType.FILE);
// Save screenshot
File destFile = new File("screenshot.png");
FileUtils.copyFile(srcFile, destFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close browser
driver.quit();
}
}
}
Output
by Sreenidhi Rajakrishnan
Implement Implicit, Explicit,
and Fluent Waits
Fluent Wait
Advanced wait with custom polling
interval and exception ignoring.
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.function.Function;
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
try {
// 1. Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://www.example.com");
// Element will be searched for up to 10 seconds
WebElement implicitElement = driver.findElement(By.id("someId"));
// 2. Explicit Wait
WebDriverWait explicitWait = new WebDriverWait(driver,
Duration.ofSeconds(20));
WebElement explicitElement = explicitWait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("loadingElement"))
);
// 3. Fluent Wait
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
Output
by Sreenidhi Rajakrishnan
Find All Broken Links on a
Webpage
Collect all links
Find elements with 'a' tag and
get href attributes
Send HTTP requests
Use HttpURLConnection to
check each URL
Identify broken links
Response codes 400+
indicate broken links
4 Report results
Compile and display list of
broken links
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
try {
// Navigate to website
driver.get("https://www.example.com");
int brokenLinks = 0;
try {
// Create connection
HttpURLConnection connection = (HttpURLConnection) new
URL(url).openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
Output
by Sreenidhi Rajakrishnan
Count Web Elements on a
Webpage
Selenium WebDriver can easily count various elements on a webpage. The code
below finds and counts all links, images, and buttons.
Navigate to Website
Initialize WebDriver Open the target webpage using the
Create a Chrome WebDriver instance get() method.
to control the browser.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
// Print results
System.out.println("Number of links: " + linkCount);
System.out.println("Number of images: " + imageCount);
System.out.println("Number of buttons: " + buttonCount);
System.out.println("Total elements counted: " + (linkCount +
imageCount + buttonCount));
} finally {
driver.quit();
}
}
}
Output
Number of links: 24
Number of images: 15
Number of buttons: 8
Total elements counted: 47
by Sreenidhi Rajakrishnan
Sort an Array Without Using
Arrays.sort()
Choose a Sorting Algorithm
We'll implement Bubble Sort as a simple example.
by Sreenidhi Rajakrishnan
Follow me on LinkedIn
// If no swapping occurred in this pass, array is
sorted
if (!swapped) {
break;
}
}
}
Output
by Sreenidhi Rajakrishnan
Find Second Largest Number
in an Array
public class SecondLargestFinder {
public static int findSecondLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
Output
by Sreenidhi Rajakrishnan
Find Duplicate Elements in
an Array
Hash Set
Use HashSet to track seen elements
Single Pass
Process array elements just once
Store Duplicates
Add duplicates to result list
by Sreenidhi Rajakrishnan
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
Output
by Sreenidhi Rajakrishnan
Check if Two Strings are
Anagrams
What are anagrams? Solution approaches
Two strings containing same 1. Sort both strings and compare
characters with same frequency but 2. Count character frequencies
different order.
3. Use character array for counting
Examples: "listen" and "silent",
"triangle" and "integral"
by Sreenidhi Rajakrishnan
Output
by Sreenidhi Rajakrishnan
Find the Missing Number in a
Sequence
public class MissingNumberFinder {
public static int findMissingNumber(int[] arr, int n) {
// Expected sum of numbers from 1 to n
int expectedSum = n * (n + 1) / 2;
Output
Missing number: 5
by Sreenidhi Rajakrishnan
Find the First Non-Repeated
Character in a String
Character Frequency Map
Use HashMap to track character counts in the string.
Two-Pass Approach
First count occurrences. Then find first character with count of 1.
Time Complexity
O(n) where n is the length of the string.
by Sreenidhi Rajakrishnan
import java.util.HashMap;
import java.util.Map;
if (result != '\0') {
System.out.println("First non-repeated character: " + result);
} else {
System.out.println("No non-repeated character found");
}
}
}
Output
by Sreenidhi Rajakrishnan
Find Common Elements
in Two Arrays
by Sreenidhi Rajakrishnan
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
Integer[] common =
findCommonElements(array1, array2);
System.out.println("Common elements: " +
Arrays.toString(common));
}
}
Output
by Sreenidhi Rajakrishnan
Count Frequency of
Elements Using HashMap
4.5
1.5
0
Apple Banana Orange Grape
by Sreenidhi Rajakrishnan
import java.util.HashMap;
import java.util.Map;
return frequencyMap;
}
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Apple", "Orange",
"Banana",
"Orange", "Orange", "Apple", "Orange", "Grape"};
System.out.println("Frequency of elements:");
for (Map.Entry<String, Integer> entry : frequency.entrySet())
{
System.out.println(entry.getKey() + ": " +
entry.getValue());
}
}
}
Output
Frequency of elements:
Apple: 3
Grape: 1
Orange: 4
Banana: 2
by Sreenidhi Rajakrishnan
Reverse Words in a Sentence
Split sentence into words
Use string split method
by Sreenidhi Rajakrishnan
return reversed.toString();
}
public static void main(String[] args) {
String sentence = "Java is a programming
language";
System.out.println("Original: " + sentence);
System.out.println("Reversed: " +
reverseWords(sentence));
}
}
Output
by Sreenidhi Rajakrishnan
Find Pairs in Array Whose
Sum Equals a Target
Define Problem
Find all pairs (a,b) where a+b equals target sum
Check Complement
For each number, look for (target-number)
Collect Pairs
Add matching pairs to result list
by Sreenidhi Rajakrishnan
by Sreenidhi Rajakrishnan
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
if (visitedNumbers.contains(complement)) {
pairs.add(new int[]{complement, num});
}
visitedNumbers.add(num);
}
return pairs;
}
by Sreenidhi Rajakrishnan
Merge Two Sorted Arrays
Start with two sorted arrays
Arrays are already in order
by Sreenidhi Rajakrishnan
int i = 0, j = 0, k = 0;
// Compare elements from both arrays and add smaller one to result
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
// Copy remaining elements from arr1, if any
while (i < n1) {
result[k++] = arr1[i++];
}
return result;
}
Output
by Sreenidhi Rajakrishnan
Convert a List to Set and Vice
Versa
List to Set Conversion
Pass List to Set constructor to remove duplicates
Use Cases
Remove duplicates or restore original order
Key Differences
List allows duplicates and maintains order; Set has unique elements
by Sreenidhi Rajakrishnan
import java.util.*;
Output
by Sreenidhi Rajakrishnan
Use of ArrayList, HashSet,
and HashMap in Code
by Sreenidhi Rajakrishnan
import java.util.*;
// HashSet demo
HashSet<String> uniqueFruits = new HashSet<>();
uniqueFruits.add("Apple");
uniqueFruits.add("Banana");
uniqueFruits.add("Apple"); // Duplicate not added
System.out.println("HashSet: " + uniqueFruits);
// HashMap demo
HashMap<String, Integer> fruitCounts = new HashMap<>();
fruitCounts.put("Apple", 5);
fruitCounts.put("Banana", 3);
fruitCounts.put("Orange", 2);
System.out.println("HashMap: " + fruitCounts);
System.out.println("Apple count: " + fruitCounts.get("Apple"));
}
}
Output
by Sreenidhi Rajakrishnan
Remove All White Spaces
from a String
Input Output
by Sreenidhi Rajakrishnan
return result.toString();
}
public static void main(String[] args) {
String text = " Java Programming is fun ";
Output
by Sreenidhi Rajakrishnan
Extract Only Digits from an
Alphanumeric String
Extract Digits
Filter out all non-digit characters
Validate Solutions
Test with various alphanumeric
inputs
by Sreenidhi Rajakrishnan
return result.toString();
}
Output
by Sreenidhi Rajakrishnan
Read Data from Excel Using
Apache POI
Dependencies Core Classes
Add Apache POI libraries to your XSSFWorkbook: For XLSX files
project. HSSFWorkbook: For XLS files
poi-5.2.3.jar Sheet, Row, Cell: For data access
poi-ooxml-5.2.3.jar
commons-io-2.11.0.jar
by Sreenidhi Rajakrishnan
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
file.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
by Sreenidhi Rajakrishnan
Output
by Sreenidhi Rajakrishnan
Capture a Screenshot in
Selenium Using Java
Set up WebDriver instance
Initialize and configure Chrome/Firefox driver
import java.io.File;
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;
by Sreenidhi Rajakrishnan
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
try {
// Navigate to website
driver.get("https://www.example.com");
// Take screenshot
TakesScreenshot scrShot = (TakesScreenshot) driver;
File srcFile = scrShot.getScreenshotAs(OutputType.FILE);
// Save screenshot
File destFile = new File("screenshot.png");
FileUtils.copyFile(srcFile, destFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close browser
driver.quit();
}
}
}
Output
by Sreenidhi Rajakrishnan
Implement Implicit, Explicit,
and Fluent Waits
Fluent Wait
Advanced wait with custom polling
interval and exception ignoring.
by Sreenidhi Rajakrishnan
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.function.Function;
public class SeleniumWaits {
public static void main(String[] args) {
// Set path to ChromeDriver
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
try {
// 1. Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://www.example.com");
// Element will be searched for up to 10 seconds
WebElement implicitElement =
driver.findElement(By.id("someId"));
// 2. Explicit Wait
WebDriverWait explicitWait = new WebDriverWait(driver,
Duration.ofSeconds(20));
WebElement explicitElement = explicitWait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("loadingElemen
t"))
);
// 3. Fluent Wait
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
Output
by Sreenidhi Rajakrishnan
Find All Broken Links on a
Webpage
Collect all links
Find elements with 'a' tag and
get href attributes
Send HTTP requests
Use HttpURLConnection to
check each URL
Identify broken links
Response codes 400+
indicate broken links
4 Report results
Compile and display list of
broken links
by Sreenidhi Rajakrishnan
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
try {
// Navigate to website
driver.get("https://www.example.com");
int brokenLinks = 0;
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
by Sreenidhi Rajakrishnan
Output
by Sreenidhi Rajakrishnan
Count Web Elements on a
Webpage
Selenium WebDriver can easily count various elements on a webpage. The code
below finds and counts all links, images, and buttons.
Navigate to Website
Initialize WebDriver Open the target webpage using the
Create a Chrome WebDriver instance get() method.
to control the browser.
by Sreenidhi Rajakrishnan
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
// Print results
System.out.println("Number of links: " + linkCount);
System.out.println("Number of images: " + imageCount);
System.out.println("Number of buttons: " + buttonCount);
System.out.println("Total elements counted: " + (linkCount +
imageCount + buttonCount));
} finally {
driver.quit();
}
}
}
Output
Number of links: 24
Number of images: 15
Number of buttons: 8
Total elements counted: 47
by Sreenidhi Rajakrishnan