Skip to content
CodeKruPro

Automation tool (Selenium) · Python

Mouse, keyboard and JavaScript

Hover, drag and drop, key presses and running JavaScript.

Learn: Mouse, keyboard and JavaScript in Selenium Python7 minute read

Clicks and typing cover most test steps. Some steps need more: a menu that opens only on hover, drag and drop, a right-click menu, or a key held down while you click. Selenium Python handles these with ActionChains. The rare things WebDriver cannot do go through execute_script, which runs JavaScript (the programming language that web pages use) inside the page. Interviewers ask about both, and especially about when JavaScript is a bad idea.

ActionChains, step by step

ActionChains collects low-level input steps (move the mouse, press a button, press a key) and sends them together when you call perform().

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

actions = ActionChains(driver)
actions.move_to_element(menu).perform()                 # hover
actions.context_click(row).perform()                    # right-click
actions.double_click(cell).perform()
actions.drag_and_drop(source, target).perform()
actions.click_and_hold(source).move_to_element(target).release().perform()
actions.key_down(Keys.CONTROL).click(link).key_up(Keys.CONTROL).perform()
actions.scroll_to_element(footer).perform()

Each method queues a step and returns the chain, so calls can be joined. pause(seconds) adds a short wait inside the chain, and reset_actions() clears queued steps. A typical hover task: move to the menu, wait for the submenu item to be visible (see Waits), then click it. The browser's own right-click menu is outside the page, so only menus drawn by the page can be clicked.

build() and perform() in Python

Interviewers who know Java ask about build() versus perform(). Python's ActionChains has no build(); perform() runs the queued steps in order. You can explain the Java idea (build makes one action object, perform builds and runs it) and then say how Python does it. The common bug is the same in both languages: a chain without perform() does nothing.

Keyboard

For a field, element.send_keys(Keys.ENTER) or element.send_keys(Keys.CONTROL, "a") is enough. Use key_down and key_up when a key must stay held during other steps, such as Shift while typing or Ctrl while clicking, and always release it. On a Mac use Keys.COMMAND instead of Ctrl.

When drag and drop does nothing

drag_and_drop sends pointer down, move and up (press the mouse button, move, let go). Pages built on HTML5 drag events (signals the browser sends to the page while you drag) sometimes ignore these simulated moves. A step-by-step chain with small moves and pauses often helps; a JavaScript helper that fires the drag events is the last resort. Assert where the item ended up, for example the id of its new parent.

execute_script

driver.execute_script("arguments[0].scrollIntoView(true);", element)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
title = driver.execute_script("return document.title;")
rows = driver.execute_script("return document.querySelectorAll('tr').length;")

Elements passed after the script appear as arguments[0], arguments[1] and so on. Values come back only with return: whole numbers as int, decimals as float, elements as WebElement, arrays as lists and objects as dicts (Python dictionaries). A script without return gives None.

Good reasons to use it: scrolling, reading a value the WebDriver API does not expose, or setting up state quickly. A JavaScript click is a last resort for an overlay (a pop-up layer that sits on top of the button) you cannot remove.

Why a JavaScript click is risky

It calls the click handler (the page code that runs when the element is clicked) directly and skips the checks a user goes through: visible, enabled, not covered. The test can pass while real users cannot click the button. Setting value through JavaScript may not fire the events the page listens to, so the app may ignore it.

Infinite scrolling

An infinite list loads more items as you reach the bottom. To load them all, scroll, wait for the count to grow, and stop when it does not, with a round limit so the test can never hang:

for _ in range(20):
    before = len(driver.find_elements(By.CSS_SELECTOR, ".item"))
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    try:
        WebDriverWait(driver, 5).until(
            lambda d: len(d.find_elements(By.CSS_SELECTOR, ".item")) > before)
    except TimeoutException:
        break

How to answer in an interview

Name the use case, then the API: "For a hover menu I use move_to_element, then an explicit wait for the submenu." For JavaScript, show arguments[0] and return, then give the risk in one sentence.

Common mistakes

  • A chain with no perform().
  • Calling build() in Python, which raises AttributeError.
  • Writing "document.title;" without return and getting None.
  • Switching every failing click to JavaScript.

Recap

ActionChains handles hover, right-click, double-click, drag and drop and held keys, and runs on perform(). execute_script passes elements as arguments and returns values only with return. Prefer real user actions, and use JavaScript with a reason you can state.

16 questions0/16 solved

StatusQuestionDifficultyAsked in
Not startedHow an ActionChains chain runs (Python)Medium
Not startedScroll to the bottom of the pageEasy-MediumAsked in: Accenture, Infosys, TCS
Not startedHover over an element with the actions APIMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedDrag a box onto a drop zoneMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedDouble-click a buttonEasy-MediumAsked in: Accenture, Capgemini, Infosys +2
Not startedRight-click (context click) a buttonEasy-MediumAsked in: Accenture, Capgemini, Infosys +2
Not startedClick and hold an element, then releaseMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedSelect all and replace text with the keyboardMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedHold Shift while typing with the actions APIMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedRead values with JavaScriptMediumAsked in: Infosys, TCS, Wipro
Not startedScroll an element into view with JavaScriptMediumAsked in: Accenture, Infosys, TCS
Not startedClick a button through JavaScriptMediumAsked in: Infosys, TCS, Wipro
Not startedChange the page with JavaScriptMediumAsked in: Infosys, TCS, Wipro
Pro+When and how do you use execute_script?MediumAsked in: Accenture, Infosys, TCS +1
Pro+What does execute_script return for a number?Easy-MediumAsked in: Infosys, TCS, Wipro
Pro+Hold Shift while typing with ActionChainsMediumAsked in: Accenture, Capgemini, Infosys +2
Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan