In Selenium WebDriver (Java), mouse hover action is used to simulate moving the mouse pointer over a web element (like a menu, button, or tooltip). It is commonly used to interact with drop-down menus or elements that appear on hover.
How to Perform Mouse Hover:
Selenium provides the Actions class to handle complex user gestures like mouse hover.
Syntax:
Actions actions = new Actions(driver); actions.moveToElement(element).perform();
Let's say you want to hover over a menu and then click a submenu item.
Sample HTML structure:
<ul id="menu"> <li class="dropdown"> <a href="#">Products</a> <ul class="submenu"> <li><a href="/products/software">Software</a></li> </ul> </li> </ul>
Selenium Java Script:
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 MouseHoverExample { public static void main(String[] args) { // Set the path to your ChromeDriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); // Initialize WebDriver WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); // Navigate to target website driver.get("https://example.com"); // Locate the main menu element WebElement menu = driver.findElement(By.xpath("//a[text()='Products']")); // Initialize Actions class Actions actions = new Actions(driver); // Perform mouse hover actions.moveToElement(menu).perform(); // Locate and click the submenu item after hover WebElement subMenu = driver.findElement(By.xpath("//a[text()='Software']")); subMenu.click(); // Optional: close the browser driver.quit(); } }
Important Points:
Always use .perform() at the end of the action.
Ensure elements are visible and interactable before hovering.
You may need to add explicit waits if submenu appears with delay.
No comments:
Post a Comment