Hover using Selenium webdriver’s ActionChains
I was recently trying to figure out how to perform a hover event using Selenium’s webdriver. The team I had previously worked on wrote a nifty function using execute_script invoking jQuery. It looked something like this:
self.driver.execute_script("jQuery('%s').mouseover()" % (hover_selector))
This didn’t always work the way I expected so I did some research and came across webdriver’s ActionChains. From Selenium-Python’s ReadTheDocs:
ActionChains are a way to automate low level interactions such as mouse movements, mouse button actions, key press, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop.
I whipped open my terminal, fired up webdriver and headed over to the trusty the-internet to give it a whirl.
The page I ran this test on was the-internet.herokuapp.com/hovers.
Here’s the code:
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Firefox() driver.get("http://the-internet.herokuapp.com/hovers") image = driver.find_element_by_css_selector("div.figure:nth-child(3)") link = driver.find_element_by_css_selector("div.figure:nth-child(3) a") # Now comes the magic ActionChains(driver).move_to_element(image).click(link).perform()
When I ran this in my console, the browser hovered over the image then clicked on the View Profile link that appears after the hover.