Mouse events like hovering, clicking on any element of the web page or the main menu and simulating the mouse actions/movements is not that tough in webDriver. Most of the actions can be performed directly in the webdriver. Here, I am going to discuss about a few of them. We use user interaction API constructor Actions with the moveToElement
method to perform the task of monitoring the movements performed by the mouse events.
In mouser action, we use Actions
(driver), object.moveToElement()
, build().
and perform()
.
Action
class is used to perform keyboard operation and mouse hover operations.
The build()
method is used to compile all the listed actions into a single step.
Below is a simple script of Mouse Hover Action. First of all, we will write the scenario of what we are going to do. Here, we will automate the http://www.myntra.com and will perform the mouse hover actions.
- Open a Firefox browser.
- Navigate to the URL.
- Maximize the window.
- Now hover on the Men’s tab present in top navigational bar.
- Select Bags and Bag-packs from Accessories.
- Select the 1st item and add it to the shopping cart.
- From shopping cart, remove the product which has been added.
- Close the browser.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class mouse_hover {
public static void main(String[] args)throws Exception{
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get("http://www.myntra.com/");
driver.manage().window().maximize();
Actions a1 = new Actions(driver);
a1.moveToElement(driver.findElement
(By.xpath("//a[@href='/shop/men?src=tn&nav_id=5']"))).build().perform();
Thread.sleep(3000L);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement
(By.xpath("//a[@href='/men-bags-backpacks?src=tn&nav_id=25']")).click();
(By.xpath("//*[text()='Categories']//following::li[1]/label']")).click();
Actions a2 = new Actions(driver);
a2.moveToElement(driver.findElement
(By.xpath("//ul[@class='results small']/li[1]"))).build().perform();
driver.findElement(By.xpath
(" //ul[@class='results small']/li[1]/div[1]//div[2]")).click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
Actions a3 = new Actions(driver);
a3.moveToElement(driver.findElement
(By.xpath("//a[@href='/checkout/cart']"))).build().perform();
driver.findElement(By.xpath("//a[@data-hint='Remove item']")).click();
driver.close();
}
}
Hope this helps beginners.
Thanks for reading.
CodeProject