Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 35 ยท Interacting with the Page

Mouse and Keyboard: the Actions API

Use Selenium ActionChains for hover menus, drag and drop, double and right clicks, key chords and scrolling, and learn why perform() is always required.

A plain click() and send_keys() handle most pages, but real interfaces ask for more: a menu that opens when you hover, a card you drag to another column, a context menu on a right click, a Shift-click to select a range. WebDriver describes these gestures with the Actions API: you build a sequence of low-level input steps, such as "move the pointer here, press the button, move again, release", and then ask the browser to run them.

In Python the builder is ActionChains; in Java it is Actions. This lesson shows the common gestures, explains how the chain works, and covers the traps: forgetting perform(), hover menus that close too early, and drag and drop that depends on how the page was built.

Selenium and a browser cannot run on this site, so the Selenium code is read-only. The runnable examples are JavaScript stand-ins that queue actions and dispatch synthetic events on fake elements, which show how a chain works internally.

Build, then perform

An action chain is a recipe. Nothing happens while you add steps. The browser acts only when you call perform():

Python
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

menu = driver.find_element(By.CSS_SELECTOR, "[data-testid='products-menu']")

ActionChains(driver).move_to_element(menu).perform()

The most common mistake is writing ActionChains(driver).move_to_element(menu) and stopping there. The chain is built, but never run, and the test continues as though nothing was expected. Always end with .perform().

Steps can be chained in a fluent style, and they run in order:

Python
(ActionChains(driver)
    .move_to_element(menu)       # hover: the menu opens
    .pause(0.3)                  # let the menu animation play
    .click(driver.find_element(By.LINK_TEXT, "Laptops"))
    .perform())

pause(seconds) adds a deliberate delay inside the chain. Use it sparingly, for animations that you cannot wait on in any other way. Normally you would rather wait for a condition (see Implicit, Explicit and Fluent Waits).

One chain, many gestures

Hover move_to_element(el)
Double and right click double_click(el), context_click(el)
Drag and drop drag_and_drop(source, target)
Key chords key_down(), send_keys(), key_up()

Every chain ends with perform().

1 / 2

Hover, double click and right click

Python
actions = ActionChains(driver)

actions.move_to_element(menu).perform()                 # hover
actions.double_click(driver.find_element(By.ID, "row-7")).perform()
actions.context_click(driver.find_element(By.ID, "file-1")).perform()   # right click

Hover menus are the classic stumbling block. The pointer moves to the target and stays there, which opens a submenu. If you then move to another element, the menu may close because the pointer left it. Click through the menu with a single chain, hovering the parent first and clicking the child last, rather than using separate steps with other actions in between. In a headless browser, hover works as well, though it depends on the window being large enough for the layout that shows the menu.

double_click sends the full sequence a user would produce, including the dblclick event. context_click sends the right button, which opens the page's own context menu if it provides one. The browser's native context menu is not part of the page and cannot be driven by Selenium.

Drag and drop

Python
source = driver.find_element(By.ID, "card-3")
target = driver.find_element(By.ID, "column-done")

ActionChains(driver).drag_and_drop(source, target).perform()

drag_and_drop is shorthand for pressing on the source, moving to the target and releasing. When it does not work, write the steps yourself, which gives you control over each one:

Python
(ActionChains(driver)
    .click_and_hold(source)
    .move_to_element(target)
    .pause(0.2)
    .release()
    .perform())

There is also drag_and_drop_by_offset(source, x, y) and move_by_offset(x, y), for sliders and canvases where there is no target element. Pages that use the browser's built-in HTML5 drag-and-drop (the draggable attribute with dragstart and drop events) sometimes react differently from pages that listen to plain mouse events. If a drag does not work, try the manual form first, and check how the page implements it before adding workarounds.

Key chords and modifiers

A chord holds a modifier key while something else happens. Use key_down and key_up, or the convenient send_keys with a modifier:

Python
from selenium.webdriver.common.keys import Keys

# Shift-click to select a range
(ActionChains(driver)
    .click(first_row)
    .key_down(Keys.SHIFT)
    .click(last_row)
    .key_up(Keys.SHIFT)
    .perform())

# Select all, then copy (Control on Windows and Linux, Command on macOS)
(ActionChains(driver)
    .key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL)
    .perform())

Each key_down must be paired with a key_up, or the modifier stays pressed for the rest of the session. If a chain is interrupted by an error, call ActionChains(driver).reset_actions() before the next gesture, and end the session with driver.quit().

Chains also have send_keys(text), which types into whichever element currently has focus, and send_keys_to_element(el, text).

Scrolling

click() scrolls an element into view when needed, but sometimes you want to scroll on purpose, for example to trigger lazy loading:

Python
ActionChains(driver).scroll_to_element(footer).perform()        # scroll until it is visible
ActionChains(driver).scroll_by_amount(0, 600).perform()         # scroll down 600 pixels

These methods arrived in Selenium 4.2. For a very old pattern, you may also see driver.execute_script("arguments[0].scrollIntoView()", el), which works everywhere but is a script, not a user gesture.

A stand-in: a chain that is queued and performed

The model below shows the two key facts about chains: steps are only recorded until perform(), and a fake element receives the same kind of low-level events a page would see. It uses EventTarget, which exists in both browsers and Node, instead of a real page.

JS A queued action chain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line of output is the whole point: before perform(), zero events had reached the element. A double click is two complete clicks followed by a dblclick event, and a right click is a press and release of the secondary button followed by contextmenu. Real browsers add details, such as the position of the pointer, but the order is the same idea.

A stand-in: drag and drop and a Shift-click chord

The second model implements a modifier that stays held between steps, then uses it to select a range in a list, and finally models a drag between two columns.

JS Key chords and drag and drop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If the second key_up were forgotten, held would still contain SHIFT, and every later click would be a Shift-click. That is exactly the bug you get in a real session when a chain with a key_down fails halfway.

Practical habits

  • Prefer a normal click() whenever it is enough, and use Actions only when a gesture needs them.
  • Keep hover-then-click inside one chain so the pointer does not leave the menu in between.
  • Replace pause() with a wait for a visible condition when you can.
  • Treat a failing drag and drop as a diagnosis task: look at how the page implements dragging before choosing a workaround.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A test builds ActionChains(driver).move_to_element(menu) and nothing is hovered. What is missing?

    An action chain only records steps. The browser acts when perform() is called.
  2. 2. Which sequence selects a range of rows with Shift-click?

    The modifier must be held while the second click happens and released afterwards.
  3. 3. What is a good first try when drag_and_drop() does not move an element?

    Spelling out the press, move and release gives control over each step and works with many drag implementations. Always check how the page handles dragging as well.
  4. 4. What does an unpaired key_down(Keys.SHIFT) cause?

    Held keys stay pressed until a key_up or until the actions are released, which can turn later clicks into Shift-clicks.

Summary

  • ActionChains (Java: Actions) records low-level pointer and key steps; nothing happens until perform().
  • Hover is move_to_element; also available are double_click, context_click, click_and_hold, release, drag_and_drop, move_by_offset and pause.
  • Chords use key_down and key_up (or send_keys with a modifier); always release what you press.
  • scroll_to_element and scroll_by_amount scroll as a user gesture (Selenium 4.2 and later).
  • Keep hover-then-click in one chain, prefer plain click() when it is enough, and investigate how a page implements dragging if drag and drop fails.

Next, handle things outside the main page in Alerts, Frames and Windows.