Sometimes, it’s not entirely convenient to scrape data from the web: sometimes one needs to hover the mouse pointer over a particular element for another one to be rendered. In this blog post, we’ll simulate a mouseover in Selenium and Python.
To mimic a mouseover event to trigger the display of a DOM element (e.g. a tooltip), we will use Selenium’s ActionChains class. It is the preferred way to create a sequence of actions like hovering over an element and clicking another one. From the Selenium (unofficial) documentation:
When you call methods for actions on the ActionChains object, the actions are stored in a queue in the ActionChains object. When you call perform(), the events are fired in the order they are queued up.
Setting up Selenium
In this first chunk of code, we load the necessary classes to run Chrome and to achieve our goal of hovering and clicking: obviously, the webdriver and the ChromeOptions class. Finally, the ActionChains class.
from selenium import webdriver from selenium.webdriver import ChromeOptions from selenium.webdriver.common.action_chains import ActionChains options = ChromeOptions() options.add_argument("--start-maximized") chrome_driver = webdriver.Chrome(options=options)
Triggering mouseover in Selenium
This next chunk is where it gets interesting. We select the necessary items using CSS selectors.
- First, we select the element that needs to be hovered. (elem_hover)
- Second, we select the element that needs to be clicked. (elem_click)
elem_hover = chrome_driver.find_element_by_css_selector('#your-element') elem_click = chrome_driver.find_element_by_css_selector('#your-element #sub-element')
In this final chunk of code, we create the sequence via an ActionsChains object which we named actions. First we will move the mouse to our elem_hover element to trigger the mouseover event that will render our elem_click element, which we will click in a second step.
The perform() method triggers the sequence.
actions = ActionChains(chrome_driver) actions.move_to_element(elem_hover) actions.click(elem_click) actions.perform()
Congratulations, we’ve triggered a mouseover in Selenium.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?