Right-click trong Selenium WebDriver

Right-click trong Selenium WebDriver
Image_right_click

Để thực hiện hành động right-click trong Selenium, chúng ta sẽ sử dụng Actions. Actions class là một thư viện được cung cấp bởi Selenium để xử lý các sự kiện bàn phím và chuột.

I. Code Snippet to Right click in Selenium

				
					Actions action = new Actions(driver);
WebElement element = driver.findElement(By.id("elementId"));
action.contextClick(element).perform();
				
			

Ở đây chúng ta sẽ khởi tạo một đối tượng của Actions class. Sau đó, chúng ta sẽ gọi hàm contextClick() để thực hiện right-click. Chỗ này các bạn nhớ lưu ý phải gọi hàm perform() thì code mới work được nhé.

II. Full code mẫu right-click

				
					package webdriver;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Action {
	WebDriver driver;
	String projectPath = System.getProperty("user.dir");
	String osName = System.getProperty("os.name");
	Actions action;
	Alert alert;
	
@BeforeClass
public void beforeClass() {
		System.setProperty("webdriver.chrome.driver", projectPath + "\\browserDrivers\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		driver.manage().window().maximize();
		action = new Actions(driver);
}
	
public void TC_01_RightClick() {
		driver.get("https://demo.guru99.com/test/simple_context_menu.html");
		
		WebElement btnRightClick =  driver.findElement(By.xpath("//span[text()='right click me']"));
		WebElement btnEdit = driver.findElement(By.xpath("//span[text()='Edit']"));
		
		action.contextClick(btnRightClick).click(btnEdit).perform();
		
		sleepInSecond(5);
		
		alert = driver.switchTo().alert();
		
		alert.accept();
		
		sleepInSecond(3);
}
	
public void sleepInSecond(int timeout) {
	try {
			Thread.sleep(timeout * 1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}
	
@AfterClass
public void afterClass() {
		driver.quit();
	}
}