Drag and Drop

 Drag and Drop

Drag and Drop is one of the common scenarios in automation. In this tutorial, we are going to study the handling of drag and drop events in Selenium WebDriver using the Actions class

1. Actions in Selenium WebDriver

Actions class in Selenium WebDriver. Using the Actions class, we first build a sequence of composite events and then perform it using Action (an interface which represents a single user-interaction). The different methods of Actions class we will be using here are-

  • clickAndHold(WebElement element) – Clicks a web element at the middle(without releasing).
  • moveToElement(WebElement element) – Moves the mouse pointer to the middle of the web element without clicking.
  • release(WebElement element) – Releases the left click (which is in the pressed state).
  • build() – Generates a composite action.

2. Code Snippet

//WebElement on which drag and drop operation needs to be performed
WebElement fromElement = driver.findElement(By Locator of fromElement);

//WebElement to which the above object is dropped
WebElement toElement = driver.findElement(By Locator of toElement);

//Creating object of Actions class to build composite actions
Actions builder = new Actions(driver);

//Building a drag and drop action
Action dragAndDrop = builder.clickAndHold(fromElement)
.moveToElement(toElement)
.release(toElement)
.build();

//Performing the drag and drop action
dragAndDrop.perform();

Switch tabs in Selenium

                                 Switch tabs in Selenium




  • We have to get all the set of tabs present in the browser.
  • When switching you might need to wait for 5 to 10 seconds for the types of browser windows to get generated.

2 Tabs:

You can switch between the tabs usingdriver.switchTo().window("handle")

String parentID = driver.getWindowHandle();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
if(parentID.equals(tabs2.get(0))) {
  driver.switchTo().window(tabs2.get(1));
}else {
  driver.switchTo().window(tabs2.get(0));
}
// perform your tasks on the newly created window



More than 2 tabs:

You need to bring the loop once you find the target window

String parentID = driver.getWindowHandle();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());

for (String handle : tabs2) {
  driver.switchTo().window(handle);
  if(driver.getTitle().equals("your wish")) {
	  break;
  }
}
// perform your tasks on the newly created window


CSV Files in Selenium

    CSV Files with selenium





    I. Concept CSV file

    It is a common format for data interchange as it is simple, compact, and used everywhere. It will open into Excel with a double click, and nearly all databases have a tool to allow import from CSV

    It is a common format for data interchange as it is simple, compact, and used everywhere. It will open into Excel with a double click, and nearly all databases have a tool to allow import from CSV

    We can handle the CSV file using the below packages :

    • Apache Commons CSV
    • Open CV

    II. Dependency CSV Integration

    First of all, you need to add an apache-commons-csv dependency in your project. If you use maven, then add the following dependency to your pom.xml file.
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-csv</artifactId>
        <version>1.5</version>
    </dependency>

    Link: https://commons.apache.org/proper/commons-csv/download_csv.cgi

    III. Reading a CSV file by Column Index

    Ex:

    import org.testng.annotations.Test;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVParser;
    import org.apache.commons.csv.CSVRecord;
    import java.io.IOException;
    import java.io.Reader;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    public class ApacheCommonsCSV {
    	@Test
    	public void readCSV() throws IOException {
    		String CSV_File_Path = "C:UsersuserDesktopq.csv";
    		// read the file
    		Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path));
    		// parse the file into csv values
    		CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
    
            for (CSVRecord csvRecord : csvParser) {
                // Accessing Values by Column Index
    			String name = csvRecord.get(0);
    			String product = csvRecord.get(1);
    			String description = csvRecord.get(2);
    			// print the value to console
    			System.out.println("Record No - " + csvRecord.getRecordNumber());
    			System.out.println("---------------");
    			System.out.println("Name : " + name);
    			System.out.println("Product : " + product);
    			System.out.println("Description : " + description);
    			System.out.println("---------------
    
    ");
            }
    	}
    }

    IV. Reading a CSV file with Column Name

    Ex:

    public class ReadWithColumnName {
    	@Test
    	public void readCSV() throws IOException {
    		String CSV_File_Path = "C:UsersuserDesktopq.csv";
    		// read the file
    		Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path));
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
                    .withHeader("Name", "Product", "Description")
                    .withIgnoreHeaderCase()
                    .withTrim());
    
            for (CSVRecord csvRecord : csvParser) {
                // Accessing values by the names assigned to each column
                String name = csvRecord.get("Name");
                String product = csvRecord.get("Product");
                String description = csvRecord.get("Description");
                System.out.println("Record No - " + csvRecord.getRecordNumber());
                System.out.println("---------------");
                System.out.println("Name : " + name);
                System.out.println("Product : " + product);
                System.out.println("Description : " + description);
                System.out.println("---------------
    
    ");
            }
    	}
    }





    Explict Wait in Selenium

       I. Explicit Wait in selenium



      ExplicitWait does not have any effect on findElement and findElements. ExplicitWait also called WebdriverWait.

      WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully.

      Syntax : WebDriverWait wait=new WebDriverWait( driver, timeoutInSeconds);

      II. alertIsPresent()

      Ex:

      public class A
      {
      	public static void main(String[] args) throws InterruptedException
      	{
      		//open firefox
      		WebDriver driver=new FirefoxDriver();
      		//open google.com
      		driver.get("https://abc.com");
      		driver.findElement(BY.xpath("//button[@class='alert']")).click();
      		WebDriverWait wait = new WebDriverWait(driver, 30 /*timeout in seconds*/);
      		//throws TimeoutException if no alert is present
      		wait.until(ExpectedConditions.alertIsPresent());
      		driver.switchTo().alert().dismiss();
      	}
      }


      III. elementToBeClickable()

      Ex:

      public class A
      {
        public static void main(String[] args) throws InterruptedException
        {
            //open firefox
            WebDriver driver=new FirefoxDriver();
            //open google.com
            driver.get("https:abc.com");
            driver.findElement(By.xpath("//button[@id='btn1']")).click();
      
        }
      }


      IV. elementToBeSelected()

      Ex:

      public class A
      {
        public static void main(String[] args) throws InterruptedException
        {
            //open firefox
            WebDriver driver=new FirefoxDriver();
            //open google.com
            driver.get("https//:abc.com");
      driver.findElement(BY.xpath("//button[@class='alert']")).click(); WebDriverWait wait = new WebDriverWait(driver, 30 /*timeout in seconds*/); //throws TimeoutException if element is not selected in given time wait.until(ExpectedConditions.elementToBeSelected(By.xpath("//input[@id='hidden]")))); } }


      V. textToBePresentInElement()

      Ex:

      public class A
      {
        public static void main(String[] args) throws InterruptedException
        {
            //open firefox
            WebDriver driver=new FirefoxDriver();
            //open google.com
            driver.get("https//:abc.com");
      driver.findElement(BY.xpath("//button[@class='alert']")).click(); WebDriverWait wait = new WebDriverWait(driver, 30 /*timeout in seconds*/); //throws TimeoutException if some text is not present in he webpage wait.until(ExpectedConditions.textToBePresentInElement(By.xpath("//input[@id='h2]")))); } }


      Implicit Wait in Selenium


        Implicitly Wait in Selenium


        Implicitly wait is one of the ways to request selenium not throw any exception until provided time. The default wait time of the selenium is 500 milliseconds, implicitly wait overrides the default wait time of the selenium.

        If the element is found before implicitly wait time, selenium moves to the next commands in the program without waiting to complete the implicitly wait time; this wait is also called dynamic wait.

        Implicit wait tries to find the element in the first go if the element is not present implicit wait tries to find the element after 500ms of first polling, if the element is not available on the second time also then implicit wait tries the third time after 500 ms of the second try and it goes on till the time reaches the 30 seconds.

        If the driver still does not find the element, then it throws an exception. Implicit wait does the same for all the elements in your program, so you just have to set it once.


        WebDriver driver = new ChromeDriver();
        // set implicit wait tme as 30 Seconds
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


        Ex:

        public class MultiValueDropdownSelectByValue {
        	public static void main(String[] args) throws Exception {
        		// set the geckodriver.exe property
        		System.setProperty("webdriver.gecko.driver", "C:/~/geckodriver.exe");
        		// open firefox
        		WebDriver driver = new FirefoxDriver();
        		// set implicitly wait time for 1 Minute
        		driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
        		// open webpage
        		driver.get("https://chercher.tech/practice/practice-dropdowns");
        		// find the dropdown using xpath
        		WebElement dropdownElement = driver.findElement(By.xpath("//select[@id='second']"));
        		// create object for Select class
        		Select dropdown = new Select(dropdownElement);
        		// select options from the dropdown options which have value as 'donut', 'burger'
        		dropdown.selectByValue("donut");
        	}
        }


         Timeunits with Implicit Wait

        • TimeUnit.NANOSECONDS : represents nano seconds (10pow-9 of a second is nanosecond)
        • TimeUnit.MICROSECONDS : represents microseconds (10pow-6 of a second is microsecond)
        • TimeUnit.MILLISECONDS : represents mill seconds (10pow-3 of a second is microsecond, i.e. 1000 milliseconds is a second)
        • TimeUnit.SECONDS : represent a second
        • TimeUnit.MINUTES : represent minutes, a minute is 60 seconds
        • TimeUnit.HOURS : represent the hour, an hour is 60 minutes
        • TimeUnit.DAYS : represents the day, a day is 24 hours