Cross_Column

Friday, 30 January 2026

Mouse & Keyboard Actions



Mouse & Keyboard Actions in Selenium with Python

🖱 Mouse & Keyboard Actions in Selenium with Python

Modern web applications use advanced UI interactions such as hover menus, right-click actions, drag and drop, keyboard shortcuts, and dynamic scrolling. Selenium provides ActionChains to handle these operations.


🧩 ActionChains Introduction

ActionChains is a Selenium class used to perform complex user interactions like mouse and keyboard operations.

from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
---

🖱 Mouse Hover

element = driver.find_element(By.ID, "menu")
actions.move_to_element(element).perform()
---

🖱 Right Click (Context Click)

element = driver.find_element(By.ID, "item")
actions.context_click(element).perform()
---

🖱 Double Click

element = driver.find_element(By.ID, "button")
actions.double_click(element).perform()
---

🧲 Drag and Drop

source = driver.find_element(By.ID, "drag")
target = driver.find_element(By.ID, "drop")

actions.drag_and_drop(source, target).perform()
---

⌨ Keyboard Actions

from selenium.webdriver.common.keys import Keys

input_box = driver.find_element(By.ID, "search")
input_box.send_keys("selenium")
input_box.send_keys(Keys.ENTER)
---

🔽 Scroll Up / Down

Using JavaScript Executor:

driver.execute_script("window.scrollBy(0, 500);")   # Down
driver.execute_script("window.scrollBy(0, -500);")  # Up
---

🎯 Scroll Into View

element = driver.find_element(By.ID, "footer")
driver.execute_script("arguments[0].scrollIntoView(true);", element)
---
🎯 Best Practices:
  • Use ActionChains for complex UI actions
  • Always wait before actions
  • Verify element visibility
  • Use scrollIntoView for hidden elements
  • Avoid hard-coded sleeps
---
🎯 Conclusion:

Mouse and keyboard actions are essential for automating modern web applications. Mastering ActionChains and JavaScript scrolling gives you full control over dynamic UI interactions.

No comments:

Post a Comment

Few More

Interview & Real-Time Examples

Advanced Selenium Automation Guide with Python 🚀 Advanced Selenium Automation with Python...