Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selenium move_to_element does not always mouse-hover

I am using python 2.7. While trying to hover the mouse on a menu item, selenium does not move the mouse to the item consistently in Chrome. Hence while clicking on a sub menu, it ends up clicking something else. However the same code throws exception in Firefox driver.

I read few posts on SO which indicates that selenium can be sometimes quirky. But I can't figure out whether I am doing something wrong.

Here is the code:

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
#driver = webdriver.Firefox()
driver.get("http://www.flipkart.com/watches/pr?p%5B%5D=facets.ideal_for%255B%255D%3DMen&p%5B%5D=sort%3Dpopularity&sid=r18&facetOrder%5B%5D=ideal_for&otracker=ch_vn_watches_men_nav_catergorylinks_0_AllBrands")
driver.maximize_window()
sleep(10)

elm_Men_Menu = driver.find_element_by_xpath("//li[@class='menu-l0 ']/a[@data-tracking-id='men']")
elm_FastTrack_Menu = driver.find_element_by_xpath("//li[@class='menu-item']/a[@data-tracking- id='0_Fastrack']")

builder = ActionChains(driver)
builder.move_to_element(elm_Men_Menu).click(elm_FastTrack_Menu).perform()
like image 824
user3262242 Avatar asked Jan 14 '15 02:01

user3262242


1 Answers

You need to do this step by step checking the visibility of the elements you are going to interact with using Explicit Waits, do not use time.sleep() - it is not reliable and error-prone:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()

driver.get("http://www.flipkart.com/watches/pr?p%5B%5D=facets.ideal_for%255B%255D%3DMen&p%5B%5D=sort%3Dpopularity&sid=r18&facetOrder%5B%5D=ideal_for&otracker=ch_vn_watches_men_nav_catergorylinks_0_AllBrands")
driver.maximize_window()

# wait for Men menu to appear, then hover it
men_menu = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//a[@data-tracking-id='men']")))
ActionChains(driver).move_to_element(men_menu).perform()

# wait for Fastrack menu item to appear, then click it
fastrack = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//a[@data-tracking-id='0_Fastrack']")))
fastrack.click()
like image 75
alecxe Avatar answered Nov 18 '22 19:11

alecxe