Right Click Action (Context Click) In Selenium

In some scenarios, we may need to do right click action / context click on an element to do some actions. We use Actions class in Selenium WebDriver to work on Mouse and Keyboard Actions. 

Scenario to be automated:
  1. Launch the web browser and open the application
  2. Find the required element and do right click on the element
  3. Go to the options ‘copy’ and get the text of it and print it
  4. Close the browser to end the program
Copy the below mentioned script and work on this scenario.
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 MouseRightClick {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "C://Program Files/eclipse/chromedriver_win32/chromedriver.exe");
WebDriver driver = new ChromeDriver();

Actions act = new Actions(driver);
WebElement button = driver.findElement(By.xpath("/html/body/div/section/div/div/div/p/span"));
act.contextClick(button).build().perform(); // Right clcik on the button
driver.findElement(By.xpath("/html/body/ul/li[3]/span")).click(); // copy
System.out.println(driver.switchTo().alert().getText()); // capturing the text present on alert box
driver.switchTo().alert().accept(); // close alert box


Post a Comment

Google Q&A Forum