How to perform mouseover function in Selenium WebDriver using Java?
To perform a mouseover (hover) action in Selenium WebDriver using Java, you can use the Actions
class. The Actions
class provides a way to create and execute complex user actions such as hover, drag and drop, etc.
Here is an example of how you can use the Actions
class to perform a mouseover action:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
public class Main {
public static void main(String[] args) {
// Initialize the WebDriver
WebDriver driver = new ChromeDriver();
// Navigate to the page
driver.get("https://www.example.com");
// Find the element to hover over
WebElement element = driver.findElement(By.id("element-id"));
// Create a new Actions object
Actions actions = new Actions(driver);
// Move the mouse over the element
actions.moveToElement(element).perform();
}
}
This code navigates to a webpage, finds an element with the ID "element-id", and moves the mouse over the element using the moveToElement()
method of the Actions
class. It then performs the action using the perform()
method.
Note that you will need to import the necessary classes and create a WebDriver
object before you can use the Actions
class. You will also need to make sure that the element is visible and interactable before you can move the mouse over it.