Human-like mouse movements with Selenium.


We can do human-like mouse movements with Selenium. This can be done with the help of the Actions class. The human-like mouse movements include right-click, double-click, mouse movement, drag and drop, and so on.

To do the mouse movement, the moveToElement method is used. To perform a right-click, the contextClick method is used. Finally, to actually execute the actions, build and perform methods should be added.

Once we right-click on an element, various options get displayed. We have to add the import org.openqa.selenium.interactions.Actions package for implementing Actions.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class RightClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      String u = " https://www.tutorialspoint.com/about/about_careers.htm";
      driver.get(u);
      // identify element
      WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
      // moveToElement and contextClick
      Actions act = new Actions(driver);
      act.moveToElement(m).contextClick().build().perform();
   }
}

Output

Updated on: 28-Dec-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements