0
0
Selenium Pythontesting~15 mins

Click and hold in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify click and hold action on a draggable element
Preconditions (3)
Step 1: Open the browser and navigate to 'https://example.com/drag'
Step 2: Locate the draggable element with id 'draggable'
Step 3: Perform a click and hold action on the draggable element
Step 4: Wait for 2 seconds while holding the click
Step 5: Release the mouse button
Step 6: Verify the draggable element's position has changed
✅ Expected Result: The draggable element moves from its original position after click and hold action
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the element's position before and after the click and hold action
Confirm the element's position has changed indicating the drag
Best Practices:
Use explicit waits to ensure elements are ready
Use ActionChains for click and hold
Avoid hardcoded sleeps except for demonstration
Use meaningful locators like By.ID
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Setup WebDriver
with webdriver.Chrome() as driver:
    driver.get('https://example.com/drag')

    wait = WebDriverWait(driver, 10)
    draggable = wait.until(EC.presence_of_element_located((By.ID, 'draggable')))

    # Get initial location
    initial_location = draggable.location

    # Perform click and hold
    actions = ActionChains(driver)
    actions.click_and_hold(draggable).pause(2).release().perform()

    # Get new location
    new_location = draggable.location

    # Assertion
    assert initial_location != new_location, f"Element location did not change: {initial_location}"

This script opens the test page and waits until the draggable element is present using an explicit wait.

It stores the element's initial position to compare later.

Using ActionChains, it performs a click and hold on the element, pauses for 2 seconds to simulate holding, then releases the mouse button.

After the action, it checks the element's new position and asserts that it has changed, confirming the drag occurred.

Explicit waits ensure the element is ready before interaction, and using By.ID locator is a best practice for clarity and speed.

Common Mistakes - 3 Pitfalls
Using time.sleep instead of explicit waits
Using incorrect locator like XPath with absolute paths
Not releasing the mouse button after click and hold
Bonus Challenge

Now add data-driven testing with 3 different draggable elements having ids 'draggable1', 'draggable2', 'draggable3'.

Show Hint