Your ultimate guide

Selenium - Mouse Actions using Python

Mouse and Keyboard Action:
    When we want to use Mouse or Keyboard actions we should create an "ActionChains" class object and we should import "from selenium.webdriver import ActionChains".
  • Syntax:
    • from selenium.webdriver import ActionChains
    • #
    •  action_obj = ActionChains(driver)

Method for ActionChains Class:
perform(): perform-function in the ActionChains is used to create a chain of actions or operations you want to perform.





move_to_element(element):  This function is used to Move the mouse point to an element.
  • Syntax:
    • a =  ActionChains(driver)
    • element = driver.find_element(By.ID, "123")
    • a.move_to_element(element).perform()




double_click(element):  This function can perform a double-click on an element.
  • Syntax:
    • a = ActionChains(driver)
    • element = driver.find_element(By.ID, "123")
    • a.double_click(element).perform()




context_click(element):  This function can perform a (Mouse)Right-Click operation on an element.
  • Syntax:
    • a = ActionChains(driver)
    • element = driver.find_element(By.ID, "123")
    • a.context_click(element).perform()




click_and_hold(element): This function can perform hold down the left mouse button on an element.
  • Syntax:
    • a =  ActionChains(driver)
    • element = driver.find_element(By.ID, "123")
    • a.click_and_hold("element").peroform()




drag_and_drop(Source, Destination): This function 
  • Syntax:
    • a = ActionChains(driver)
    • source = driver.find_element(By.ID, "123")
    • destination = driver.find_element(By.ID, "ABC")
    • a.drag_and_drop(source, destination).perform()




Note: if the element = None, then it performs the action on the current mouse position.




Program:
  1. from selenium import webdriver
  2. from selenium.webdriver import ActionChains
  3. from selenium.webdriver.common.by import By

  4. driver = webdriver.Chrome()
  5. driver.get("https://testingcolleges.blogspot.com/2023/08/alert-demo-pages.html")

  6. action = ActionChains(driver)
  7. # Double-Click
  8. double = driver.find_element(By.ID, "doubleclick")
  9. action.move_to_element(double).double_click().perform()
  10. time.sleep(2)

  11. # Right-Click
  12. right = driver.find_element(By.ID, "rclick")
  13. action.context_click(right).perform()
  14. time.sleep(2)

  15. driver.close()
OUTPUT:
    


No comments:

Post a Comment