Thursday, 15 June 2023

Published June 15, 2023 by with 0 comment

Handling Dynamic Web Elements: Techniques for dealing with dynamic web elements that change their attributes or locations during runtime.

Introduction:

In web application testing, dynamic web elements that change their attributes or locations during runtime can pose challenges. However, with the right techniques and strategies, we can effectively handle these dynamic elements using Selenium in Java. In this blog post, we will explore various techniques and provide code snippets to handle dynamic web elements successfully.

Understanding Dynamic Web Elements:

Dynamic web elements refer to elements on a webpage that change their attributes or locations dynamically. This can occur due to dynamic content loading, AJAX calls, page refreshes, or changes in the DOM structure. Examples of dynamic elements include dropdowns, menus, pop-ups, modals, or elements that load asynchronously.

Techniques for Handling Dynamic Web Elements:

1. Implicit and Explicit Waits:

Both implicit and explicit waits are essential for handling dynamic web elements. Implicit waits allow the driver to wait for a specified amount of time for an element to be present on the page. Explicit waits enable you to wait for specific conditions to be met before proceeding. Here's an example of using explicit wait with ExpectedConditions in Selenium:


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-testid='dynamic-element']")));

2. Dynamic XPath or CSS Selectors:

XPath and CSS selectors are powerful techniques for locating elements. When dealing with dynamic elements, you can utilize dynamic values within XPath or CSS selectors to locate the element. Here's an example using XPath with a dynamic attribute value:


WebElement element = driver.findElement(By.xpath("//input[contains(@class, 'dynamic-input-')]"));

3. Relational Locators:

Dynamic elements are often located relative to other stable elements on the page. By identifying the stable parent or sibling elements, you can navigate to the dynamic element using XPath or CSS selectors. Here's an example using XPath with a relational locator:


WebElement parentElement = driver.findElement(By.id("parent-element")); WebElement dynamicElement = parentElement.findElement(By.xpath(".//span[contains(@class, 'dynamic-span')]"));

4. Refreshing the DOM:

In some cases, dynamic elements may not be immediately available in the DOM. You can try refreshing the DOM by reloading the page or waiting for a specific event to trigger the appearance of the dynamic element. Here's an example of refreshing the page to handle dynamic content:


driver.navigate().refresh(); WebElement element = driver.findElement(By.id("dynamic-element"));

5. JavaScript Execution:

JavaScript can be used to interact with dynamic elements directly. By executing JavaScript commands using Selenium, you can manipulate the DOM or trigger events on dynamic elements. Here's an example of executing JavaScript code to handle a dynamic element:


JavascriptExecutor js = (JavascriptExecutor) driver; WebElement element = (WebElement) js.executeScript("return document.getElementById('dynamic-element')");

Conclusion:

Handling dynamic web elements is crucial for successful web application testing using Selenium in Java. By applying the techniques discussed above and utilizing the provided code snippets, you can effectively handle dynamic elements that change their attributes or locations during runtime. It is important to adapt these techniques to your specific application and regularly update your automation strategy as the dynamic elements evolve. With these approaches and a proactive approach, you can create robust and reliable automated tests, even in the presence of dynamic web elements.

Read More

Monday, 29 March 2021

Published March 29, 2021 by with 0 comment

Different Approaches For Maximizing Browser Window In Selenium Webdriver

Hello learners,  

Maximizing the browser window manually is a very simple task. But when we do it through Automation then there are number of ways we can do this. Generally, when the questions like what are the different ways we can maximize a window in Selenium? or What are different approaches for maximizing window in Selenium? asked during interviews, we ended up giving answers like by using maximize() method of the driver. But apart from that below are the different approaches that we can use for maximizing browser window in Selenium WebDriver.


Approch 1. Using maximize() Method:

We have different methods under driver.manage().window(). 

So, here we will use maximize() method to maximize browser window. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class UsingMaximizeFunction {

	public static void main(String[] args) {

		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver();

		// Maximize current window
		driver.manage().window().maximize();

		// Navigate to a website
		driver.get("https://www.myautomationlab.com/");

		// Close the browser
		driver.quit();

	}

}

Approch 2. Using fullscreen() Method:

As mentioned in Approch 1, we have different methods under driver.manage().window(). 

So, here we will use fullscreen() method to maximize browser window. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class UsingFullScreenFunction {

	public static void main(String[] args) throws InterruptedException {

		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver();

		// Navigate to a website
		driver.get("https://www.myautomationlab.com/");

		// Maximize current window using "fullscreen" function
		driver.manage().window().fullscreen();

		Thread.sleep(3000);

		// Close the browser
		driver.quit();
	}

}

Approch 3. Using  setSize() Method:

Dimension class is used to set height and width of the object. 

So, here we can set the height and width of the browser as per our requirement. 

To do browser window maximization one should know the height and width of the maximize window. This will differ based on the screen resolution of your device. 

To use dimension class first create the object of Dimension class. 

Then pass that dimension object to setSize() method as driver.manage().window().setSize(dimension object) method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class UsingWindowSize {

	public static void main(String[] args) {

		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver();

		// Maximize current window by setting windows size
		Dimension dim = new Dimension(1280, 860);
		driver.manage().window().setSize(dim);

		// Navigate to a website
		driver.get("https://www.myautomationlab.com/");

		// Close the browser
		driver.quit();

	}

}

Approch 4. Using ChromeOptions window-size:

ChromeOptions class is used for customizing the ChromeDriver session. 

So, when we launch any browser using Selenium then it opens up with given configurations. 

First, create the ChromeOptions class object. 

Then add arguments to that object as chromeOptions.addArguments("window-size=1280,860"). Here 1280 is the width and 860 is the height for maximizing a window. You can pass width and height as per your requirement there. 

Then while doing Webdriver initialization we need to pass the instance of ChromeOptions class. 

After that, it will launch the browser with maximize browser window. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class UsingChromeOptionsWindowSize {

	public static void main(String[] args) {

		// Maximize current window using ChromeOptions "window-size"
		ChromeOptions chromeOptions = new ChromeOptions();
		chromeOptions.addArguments("window-size=1280,860");

		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver(chromeOptions);

		// Navigate to a website
		driver.get("https://www.myautomationlab.com/");

		// Close the browser
		driver.quit();

	}

}

Approch 5. Using ChromeOptions --start-fullscreen:

We can use --start-fullscreen method of ChromeOptions. 

First, create the ChromeOptions class object. 

Then add arguments to that object as chromeOptions.addArguments("--start-fullscreen"). Here "--start-fullscreen" is a keyword that you have to use as it is.

Then while doing Webdriver initialization we need to pass the instance of ChromeOptions class. 

After that, it will launch the browser with maximized browser window. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class UsingChromeOptionsStartFullscreen {

	public static void main(String[] args) {

		// Maximize current window using ChromeOptions "--start-fullscreen"
		ChromeOptions chromeOptions = new ChromeOptions();
		chromeOptions.addArguments("--start-fullscreen");

		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver(chromeOptions);

		// Navigate to a website
		driver.get("https://www.myautomationlab.com/");

		// Close the browser
		driver.quit();

	}

}

Approch 6. Using ChromeOptions --start-maximized/--kiosk:

We can use --start-maximized/--kiosk method of ChromeOptions. 

First, create the ChromeOptions class object. 

Then based upon our operating system we need to add arguments to that object.

If the operating system is windows then add arguments to ChromeOption object as chromeOptions.addArguments("--start-maximized"). Here "--start-maximized" is a keyword that you have to use as it is.

If the operating system is MAC/Linux then add arguments to ChromeOption object as chromeOptions.addArguments("--kiosk"). Here "--kiosk" is a keyword that you have to use as it is.

Then while doing Webdriver initialization we need to pass the instance of ChromeOptions class. 

After that, it will launch the browser with maximized browser window.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class UsingChromeOptionsStartMaximized {

	public static void main(String[] args) {

		ChromeOptions chromeOptions = new ChromeOptions();

		if (System.getProperty("os.name").startsWith("Windows")) {

			// To maximize window in Windows system use "--start-maximized"
			chromeOptions.addArguments("--start-maximized");
		} else {

			// To maximize window in Mac & linux system use "--kiosk"
			chromeOptions.addArguments("--kiosk");
		}

		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver(chromeOptions);

		// Navigate to a website
		driver.get("https://www.myautomationlab.com/");

		// Close the browser
		driver.quit();

	}

}

The Source Code for above topic is available on GitHub Repository, You can get it from this URL:- 

Read More

Saturday, 27 March 2021

Published March 27, 2021 by with 1 comment

Some Cool Facts About Main Method in Java

Hello learners,  

In this post, we'll learn about some basic concepts related to Main method in Java. But before that lets understand what is main method, its importance, how it interacts with JVM etc. 

1. What is main method in Java?

Main method is the entry point for every Java program. When you execute certain class that time Java compiler first search for main method for that class, after finding the main method it starts it's execution. Below is the figure for illustrating meaning of every word in declaration of  main method.

                

                 

In the above figure public is  a Access Modifier that means the main method is called by JVM from any class, package, subclass etc. static is a Keyword that means we don't need to create objects of main method it can be directly called with the help of class. Void is a return type that means main method does not return any value. main is a method name. And lastly main method can accept one argument of type String Array.

2. What happens to Java program if main method is not present.

It will give byte code verification error as "Main method not found in class".  Now, this will be a error and not exception since the program has not started its execution yet. Prior to JDK7 main method declaration was not mandatory but after JDK7 it is mandatory to define method for execution of program.

3. Can we overload main method in Java?

Yes, we can surely do this. We can declare multiple methods with the name as main but the parameters will be different. Let's say we have declare four different main method with different parameters as String array, Single String, Single Integer and with two Integer. And calling the other mains from first main method. Now, since the data type of parameters are different in every case so the main method execution is happening properly.

Code: 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package javaProgramsforInterview;

public class JavaPrograms {
	public static void main(String[] args) {

		System.out.println("Main Method-1");
		main("my automation lab");
		main(50);
		main(20, 40);
	}

	public static void main(String args) {

		System.out.println("Main Method-2");
	}

	public static void main(int a) {

		System.out.println("Main Method-3");
	}

	public static void main(int a, int b) {

		System.out.println("Main Method-4");
	}
}

Output:

1
2
3
4
Main Method-1
Main Method-2
Main Method-3
Main Method-4

4. Can we call main method from another class?

Yes, we can surely do this. Since main method is static in nature and static methods we can call by using ClassName.method() from another classes. 

Code: 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package javaProgramsforInterview;

public class ClassA {

	public static void main(String[] args) {

		System.out.println("This is Java Class A");
		ClassB.main(args);
	}

}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package javaProgramsforInterview;

public class ClassB {

	public static void main(String[] args) {

		System.out.println("This is Java Class B");

	}

}

Output:

1
2
This is Java Class A
This is Java Class B

5. What happens if we call main methods of two classes within each other

When we call main methods of two classes within each other then the output will go in infinite loop. In the above example let's say we are calling main method of ClassB in ClassA and main method of ClassA in ClassB then when we execute class A first it will execute all the methods for A and then the control will go to ClassB it will execute all methods of ClassB but since in ClassB we have called main method of ClassA then the control will again go to ClassA and it will continue till infinite loop.

6. Can we Override the main method?
No, we can't do this. Since main method is static in nature we can not override it. In method overriding we change the implementation part of methods having same name. Now, for changing the implementation part we need to create objects within that method but for static methods we don't need to create its object it gets directly called by it's class name. Suppose, if we have multiple main methods with method name as "main" and same parameters then it will be very confusing that which main method to be executed. Therefore, it is not possible to override a main() method.

Read More

Tuesday, 23 March 2021

Published March 23, 2021 by with 0 comment

Removing duplicate characters from given string without using Java Built in functions.

Approch 1

First will convert String to Characters by using toCharArray function. After that will store that CharArray to Set it will automatically remove all duplicates. And then will use StringBuilder function to reconstruct that String.


Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package javaProgramsforInterview;
 
import java.util.LinkedHashSet;
import java.util.Set;
 
public class RemovingDuplicates1 {
 
	public static void main(String[] args) {
		String string = "samplestringfortest";
 
		char[] chars = string.toCharArray();
		Set<Character> charSet = new LinkedHashSet<Character>();
		for (char c : chars) {
			charSet.add(c);
		}
 
		StringBuilder sb = new StringBuilder();
		for (Character character : charSet) {
			sb.append(character);
		}
		System.out.println(sb.toString());
	}
}
Output:

sampletringfo


Approch 2

First will convert String to Characters by using toCharArray function. After that we will compare n’th letter from zero to (n-1) index to all the letters of string. Then we will use a boolean flag to check the duplicate letter. If a duplicate letter is found then will turn off the flag and will not append the letter to the String. If there is no duplicate letter then we will keep the flag value as true and will append the letter to string. For string reconstruction we are using StringBuilder function.


Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package javaProgramsforInterview;
 
public class RemovingDuplicates2 {. 
 
	public static void main(String[] args) {
		String string = "samplestringfortest";
		char[] chars = string.toCharArray();
		StringBuilder sb1 = new StringBuilder();
 
		for (int i = 0; i < chars.length; i++) {
			boolean flag = true;
			for (int j = 0; j < i; j++) {
				if (chars[j] == chars[i]) {
					flag = false;
					break;
				}
			}
			if (flag) {
				sb1.append(chars[i]);
			}
		}
		System.out.println(sb1.toString());
	}
}
Output:

sampletringfo

Read More

Tuesday, 13 March 2018

Published March 13, 2018 by

Nth Even Fibonacci Number

Nth Even Fibonacci Number

I this post, we'll learn about how to calculate Nth Even Fibonacci Number.

The Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones.


In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation,

 Fn = Fn-1 + Fn-2  with seed values

 F0 = 0 and F1 = 1.

The even number Fibonacci sequence is : 0, 2, 8, 34, 144, 610, 2584…. We have to find nth number in this sequence.

The formula of even Fibonacci number =  ((4*evenFib(n-1)) + evenFib(n-2));


The Below Code shows how to calculate Nth Even Fibonacci Number in Java. 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class NthEvenFibonacciNumber {
	
	public static void main(String[] args) {
		
		// Here we are passing nth Number
		int nthNumber = 3;
		//Calling the getEvenNumber Method And Printing the Nth Even Fibonacci Number number
		System.out.println(getEvenNumber(nthNumber));
	}

	public static int getEvenNumber(int nthNumber) {
		if (nthNumber < 1) {
			return nthNumber;
		} else if (nthNumber == 1) {
			return 2;
		} else {
			//Formula to calculate Nth Even Fibonacci Number  Fn = 4*(Fn-1) + Fn-2
			return ((4 * getEvenNumber(nthNumber - 1)) + getEvenNumber(nthNumber - 2));
		}
	}

}
            
Output :- 34 



If You like my post please like & Follow the blog, And get upcoming interesting topics.
Read More

Sunday, 11 March 2018

Published March 11, 2018 by

How to handle Lazy Loading Webpage

Hello Learners,

Just like humans sometimes webpage elements also get lazy. We have often seen lazy loading-related scenarios on different e-commerce and other social media sites but, we are not aware about it that it is called as Lazy Loading. Also, how to handle such Lazy webelements through Selenium is a tricky question. But no worries!!  Let's move ahead in the post and find out what is this Lazy Loading & How to handle it?

What is Lazy Loading?

There is a new technology in web development, which is called Lazy Loading. This makes your web page lighter and loads fast

How it works is that it loads the page only what is visible on the screen, and on scrolling down the page, it again loads the rest of the page. So it loads only the visible part of the webpage, not the whole web page at one go. 

How to handle Lazy Loading?

How to handle Lazy Loading?

So the solution to your problem is to scroll down the web page where your element is visible. Make sure you do not scroll it down completely at a go, as if you directly reach the bottom of the page, then again it will not load the middle web page. 

So your interested element will be active only when you load that part of the page.

Here to scroll the page we are using Java- Script

The Syntax is as follows:-

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

So, the general Steps to Handle Lazy Loading scenarios are:-
  1. First, redirect to the page where you are getting a lazy loading scenario
  2. Define JavascripExecutor
  3. Use JavascripExecutor to scroll to page height
  4. Wait for 1-2 seconds for new images/content to get load
  5. Here you can put condition to check whether the page has reached to the bottom or not. By comparing total current elements loaded after scrolling down page with the previous total elements loaded.
  6. Again repeat step no. 3 to 5 to scroll the page if page has not reached to the bottom.

The Below Code shows the lazy loading handling on Pinterest. 

The Source Code for this topic is available on GitHub Repository, You can get it from this URL:-


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.lazyloading.ui.test;

import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
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.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class LazyLoading {

	WebDriver driver;
	String emailId = "emailId";
	String password = "password";

	@BeforeMethod
	public void setup() {

		System.setProperty("webdriver.chrome.driver", "/Users/ShubhamPatil/Desktop/chromedriver");
		driver = new ChromeDriver();
		driver.get("https://www.pinterest.com");
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
	}

	@Test
	public void test() throws InterruptedException {

		driver.findElement(By.xpath("//div[text()='Log in']")).click();
		driver.findElement(By.id("email")).sendKeys(emailId);
		driver.findElement(By.id("password")).sendKeys(password);
		driver.findElement(By.xpath("(//div[text()='Log in'])[2]")).click();

		Assert.assertTrue(driver.findElement(By.xpath("//span[text()='Home']")).isDisplayed(),
				"Home Page is not displayed");

		By elementLocator = By.xpath("//img[@loading='auto']");

		// Calling the locateElement method, to fetch all elements
		locateElement(elementLocator);
	}

	public void locateElement(By elementLocator) throws InterruptedException {
		WebDriverWait wait = new WebDriverWait(driver, 10);
		JavascriptExecutor js = (JavascriptExecutor) driver;

		// Initial element count
		int elementCount = driver.findElements(elementLocator).size();

		while (true) {
			// javascriptexecutor to scroll the page
			js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

			wait.ignoring(NoSuchElementException.class)
					.until(ExpectedConditions.invisibilityOfElementLocated(elementLocator));

			// Wait to load the new elements
			Thread.sleep(2000);

			// Check if the last fetch element count is same as new count,
			// If it's same then we already have fetch all the elements on the page.
			if (driver.findElements(elementLocator).size() == elementCount)
				break;

			// fetch the latest elements count
			elementCount = driver.findElements(elementLocator).size();
		}
	}

}
The Source Code for this topic is available on GitHub Repository, You can get it from this URL:-
If You like my post please like & Follow the blog, And get upcoming interesting topics.
Read More