Action class in Selenium Webdriver

asked 3 months ago

Action class in Selenium webdriver is used to handle the keyboard and mouse events. On the web page, apart from typing, there are different actions needed to perform through the keyboard such as pressing combinations of the keys and there are different actions using mouse, drag and drop, right-click, double click, click and hold, etc..In order to handle keyboard and mouse actions selenium webdriver provides an Action class.

The available methods in the class,

 

action_class_seleniumwebdriver

 

To hover the element :

 

Syntax :

Actions act = new Actions(driver);
act.moveToElement("webelement").build().perform();

 

Example:

Go to https://www.qafeast.com/demo, click Hyperlink Tab,

Actions act = new Actions(driver);
act.moveToElement(driver.findElement(By.xpath("//a[text()='Web browser automation']"))).build().perform();

 

To Right click

 

Syntax:

Actions act = new Actions(driver);
act.moveToElement("webelement").contextClick().build().perform();

 

Example:

Go to https://www.qafeast.com/demo, click Hyperlink Tab,

Actions act = new Actions(driver);
act.moveToElement(driver.findElement(By.id("hot-spot"))).contextClick().build().perform();

 

To Double Click:

 

Syntax:

Actions act = new Actions(driver);
act.doubleClick("webelement").build().perform();

 

Example:

Go to https://www.qafeast.com/demo, click Context Menu Tab,

Actions act = new Actions(driver);
act.doubleClick(driver.findElement(By.xpath("//div[@class='doubleclick-wrap']/p"))).build().perform();

 

In Selenium Csharp

 

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;

namespace ConsoleApp1
{
   internal class SeleniumTest
   {
       static IWebDriver driver;
       static void Main(string[] args)
       {
          
           driver = new ChromeDriver(@"\\Driver\\chromedriver.exe");
           //Implicit Wait:
           driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
           driver.Navigate().GoToUrl("https://qafeast.com/demo");
           driver.FindElement(By.XPath("//label[text()='Hyperlink']")).Click();
           //To hover the element : 
           Actions action = new Actions(driver);
          
          action.MoveToElement(driver.FindElement(By.XPath("//a[text()='Web browser automation']"))).Build().Perform();
           //To Right click && Context menu click: 

           driver.FindElement(By.XPath("//label[text()='Context Menu']")).Click();
           action.MoveToElement(driver.FindElement(By.Id("hot-spot"))).ContextClick().Build().Perform();

           //To Double Click:
           driver.FindElement(By.XPath("//label[text()='Double Click']")).Click();
           action.DoubleClick(driver.FindElement(By.XPath("//div[@class='doubleclick-wrap']/p"))).Build().Perform();
           driver.Quit();  
       }
   }
}