How To Perform Right Click Action (Context Click) In Selenium
Perform Right Click Action 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. Check out the below link for detailed explanation of Actions Class.
Must Read:Â Actions Class in Selenium WebDriver
Coming back to the current post, here we I take a scenario to do right click action on an element and get the text of an item
Scenario to be automated:
- Launch the web browser and open the application
- Find the required element and do right click on the element
- Go to the options ‘copy’ and get the text of it and print it
- Close the browser to end the program
Copy the below mentioned script and work on this scenario.
Given clear explanation in the comments section with in the program itself. Please go through it to understand the flow.
package softwareTestingMaterial; 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; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test; public class ActionsClass { @Test public void textInCaps() throws InterruptedException{ //Instantiating the WebDriver interface. System.setProperty("webdriver.chrome.driver", "D:\\Selenium Environment\\Drivers\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //Open the required URL driver.get("http://swisnl.github.io/jQuery-contextMenu/demo.html"); //To maximize the browser driver.manage().window().maximize(); //Create an object 'action' of an Actions class Actions action = new Actions(driver); By locator = By.cssSelector(".context-menu-one"); //Wait for the element. Used Explicit wait WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.presenceOfElementLocated(locator)); WebElement rightClickElement=driver.findElement(locator); //contextClick() method to do right click on the element action.contextClick(rightClickElement).build().perform(); WebElement getCopyText =driver.findElement(By.cssSelector(".context-menu-icon-copy")); //getText() method to get the text value String GetText = getCopyText.getText(); //To print the value System.out.println(GetText); //To close the browser driver.close(); } }
If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.