What is the difference between action and actions in the context of selenium?

100    Asked by ConnorPeake in QA Testing , Asked on Apr 17, 2024

I am currently designing a test scenario using Selenium. How can I differentiate between using “action” and “actions” in my test scripts? 

Answered by Connor Peake

In the context of selenium, here is the difference given below between action and actions in selenium:-

Action refers to a single interaction with an element, like clicking a button or entering text into a field. It is generally used with methods like click(), sendkeys(), etc.

Actions refer to mainly the series of Interactions that are performed as a sequence. It is generally used for operations that are complex like drag and drop, mouse hovering or even performing key combinations.

Here is the example given which would show the use of action and actions in selenium WebDriver by using the Java programming language:-

Import org.openqa.selenium.By;
Import org.openqa.selenium.WebDriver;
Import org.openqa.selenium.WebElement;
Import org.openqa.selenium.chrome.ChromeDriver;
Import org.openqa.selenium.interactions.Actions;
Public class SeleniumActionsExample {
    Public static void main(String[] args) {
        // Set the path to the chromedriver executable
        System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
        // Initialize WebDriver
        WebDriver driver = new ChromeDriver();
        // Open the webpage
        Driver.get(https://example.com);
        // Find the element to interact with using “action”
        WebElement buttonElement = driver.findElement(By.id(“myButton”));
        // Perform a single action – clicking the button
        Actions action = new Actions(driver);
        Action.click(buttonElement).build().perform();
        // Pause for 2 seconds to see the result
        Try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Find source and target elements for a drag-and-drop operation using “actions”
        WebElement sourceElement = driver.findElement(By.id(“source”));
        WebElement targetElement = driver.findElement(By.id(“target”));
        // Perform a series of actions – drag-and-drop from source to target
        Actions actions = new Actions(driver);
        Actions.moveToElement(sourceElement)
                .clickAndHold()
                .moveToElement(targetElement)
                .release()
                .build()
                .perform();
        // Pause for 2 seconds to see the result
        Try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Close the browser
        Driver.quit();
    }
}


Your Answer

Interviews

Parent Categories