0
0
Selenium Pythontesting~15 mins

Find element by ID in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify login button is clickable by finding element using ID
Preconditions (1)
Step 1: Locate the login button using its ID 'loginBtn'
Step 2: Click the login button
✅ Expected Result: The login button is found by ID and clicked successfully without errors
Automation Requirements - selenium
Assertions Needed:
Assert that the login button element is present before clicking
Assert that after clicking, the current URL changes to the dashboard page URL 'https://example.com/dashboard'
Best Practices:
Use explicit waits to wait for the element to be present and clickable
Use By.ID locator strategy for finding the element
Use try-except blocks to handle exceptions gracefully
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Initialize the Chrome driver
with webdriver.Chrome() as driver:
    driver.get('https://example.com/login')

    wait = WebDriverWait(driver, 10)

    # Wait until the login button is present and clickable
    login_button = wait.until(EC.element_to_be_clickable((By.ID, 'loginBtn')))

    # Assert the login button is displayed
    assert login_button.is_displayed(), 'Login button is not visible'

    # Click the login button
    login_button.click()

    # Wait until URL changes to dashboard
    wait.until(EC.url_to_be('https://example.com/dashboard'))

    # Assert the URL is correct
    assert driver.current_url == 'https://example.com/dashboard', 'Did not navigate to dashboard after login'

This script uses Selenium WebDriver with Python to automate the manual test case.

First, it opens the login page URL.

Then it uses an explicit wait to find the login button by its ID 'loginBtn' and waits until it is clickable.

It asserts the button is visible before clicking it.

After clicking, it waits for the URL to change to the dashboard URL and asserts the navigation succeeded.

Using explicit waits ensures the test does not fail due to timing issues.

Using By.ID locator is the most direct and reliable way to find the element by its unique ID.

Common Mistakes - 3 Pitfalls
Using time.sleep() instead of explicit waits
{'mistake': 'Using find_element_by_id() which is deprecated', 'why_bad': 'Deprecated methods may be removed in future Selenium versions and cause code breakage.', 'correct_approach': "Use driver.find_element(By.ID, 'id_value') as per the latest Selenium API."}
Not checking if the element is visible before clicking
Bonus Challenge

Now add data-driven testing with 3 different login button IDs to verify each is clickable

Show Hint