There will be situations where it is required to click on the item of the drop down menu for e.g. Go toToolsQA demo online store > Click on Product category link on the top menu > Then select any of the items from the drop down menu:
See the screen shot below:
One way of doing this is by using Action class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
public class mouseHover{
public static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.onlinestore.toolsqa.com");
WebElement element = driver.findElement(By.linkText("Product Category"));
Actions action = new Actions(driver);
action.moveToElement(element).build().perform();
driver.findElement(By.linkText("iPads")).click();
}
}
|
It can be done differently like this:
|
|
WebElement element = driver.findElement(By.linkText("Product Category"));
Actions action = new Actions(driver);
action.moveToElement(element).moveToElement(driver.findElement(By.linkText("iPads"))).click().build().perform();
|
With some of the browser it happens that once mouse hover action is performed, the menu list disappear with in the fractions of seconds before Selenium identify the next submenu item and perform click action on it. In that case it is better to use ‘perform()’ action on the main menu to hold the menu list till the time Selenium identify the sub menu item and click on it.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
WebElement element = driver.findElement(By.linkText("Product Category"));
Actions action = new Actions(driver);
action.moveToElement(element).perform();
WebElement subElement = driver.findElement(By.linkText("iPads"));
action.moveToElement(subElement);
action.click();
action.perform();
|
Note: The above codes work most of the time but you may see different behaviour with different OS machines and different browsers.
No comments:
Post a Comment