Skip to content
Home » Simulate mouseover in Selenium (Python)

Simulate mouseover in Selenium (Python)

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.

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

7 thoughts on “Simulate mouseover in Selenium (Python)”

  1. Современная клиника предоставляет всестороннюю медицинскую помощь для всей семьи.
    Команда профессионалов обладают высокой квалификацией и работают на новейшей аппаратуре.
    В клинике созданы все удобства для прохождения обследований.
    Мы предлагаем гибкие программы лечения для каждого пациента.
    Мы заботимся о поддержанию высокого уровня сервиса.
    Все клиенты могут ожидать качественное лечение в удобное время.
    rocketmaxx.com

  2. На этом сайте вы можете найти самые актуальные события из мира автомобилей.
    Информация обновляется регулярно, чтобы вы быть в курсе всех значимых событий.
    Автоновости охватывают все аспекты автомобильной жизни, включая новые модели, технологии и события.
    articlesjust4you.com
    Мы следим за всеми тенденциями, чтобы предоставить вам максимально точную информацию.
    Если вы интересуетесь автомобилями, этот сайт станет вашим лучшим другом.

  3. Within this platform, access real-time video interactions.
    Searching for engaging dialogues career-focused talks, you’ll find a solution tailored to you.
    Live communication module crafted to connect people from around the world.
    Featuring HD streams plus excellent acoustics, each interaction becomes engaging.
    Participate in open chat spaces initiate one-on-one conversations, depending on your needs.
    https://videochat18.ru/
    The only thing needed is a stable internet connection plus any compatible tool to get started.

  4. Этот увлекательный информационный материал подарит вам массу новых знаний и ярких эмоций. Мы собрали для вас интересные факты и сведения, которые обогатят ваш опыт. Откройте для себя увлекательный мир информации и насладитесь процессом изучения!
    Подробнее можно узнать тут – https://medalkoblog.ru/

Leave a Reply

Your email address will not be published. Required fields are marked *