Hover event in Selenium

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()
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

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.



Install Selenium for fun (and profit!)

So you want to install Selenium?


There are a couple ways to install Selenium on your system. If you already have PIP installed, it’s as easy as running the following from your command line:

pip install -U selenium

This will check to see if you already have selenium installed and, if you do, upgrade it if there is one available. If you don’t, it’ll install the python bindings for Selenium.

Python bindings?! Yep, Selenium comes in several flavors. Head over to the download page for Selenium to check them out and find the programming language you’re most familiar with.

Another way to install Selenium is to download the source distribution from PyPi, unarchive it, and install it using the following Python command:

python setup.py install

This will run the setup.py via the Python version that’s installed on your system.


The commands above should be system-independent meaning you can run them on Windows, Linux, Mac, etc.selenium logo

Install pip on Windows

pip is a package manager for Python. It makes it easy to install and upgrade Python packages using the command line. Installing a Python package using pip is as easy as opening the command line and typing:

pip install -U requests

  1. “requests” is the package you want to install
  2. “install” tells pip you want to install a package. If you want to uninstall a package simply type “uninstall”.
  3. The “-U” flag tells pip that if the package is already installed, then upgrade it.