Selenium move_to_element doesn't always hover

I am using python 2.7. When you try to hover over a menu item, selenium does not move the mouse into the item sequentially in Chrome. Therefore, when you click on a submenu, it ends by clicking on something else. However, the same code throws an exception in the Firefox driver.

I read several posts about SO, which indicates that selenium is sometimes bizarre. But I can’t understand that 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() 
+7
python google-chrome selenium selenium-webdriver
source share
1 answer

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() 
+12
source share

All Articles