Verify login button using XPath with contains and starts-with
Preconditions (1)
✅ Expected Result: The login button is found using both XPath expressions, is visible, enabled, and has the text 'Log In'
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 # Setup WebDriver (assuming chromedriver is in PATH) driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) try: # Open login page driver.get('https://example.com/login') # Locate login button using contains() on class attribute login_button_contains = wait.until( EC.visibility_of_element_located( (By.XPATH, "//button[contains(@class, 'login-btn')]") ) ) # Assert button is displayed and enabled assert login_button_contains.is_displayed(), "Login button (contains) is not displayed" assert login_button_contains.is_enabled(), "Login button (contains) is not enabled" # Locate login button using starts-with() on id attribute login_button_starts = wait.until( EC.visibility_of_element_located( (By.XPATH, "//button[starts-with(@id, 'loginBtn')]") ) ) # Assert button text is 'Log In' button_text = login_button_starts.text assert button_text == 'Log In', f"Expected button text 'Log In' but got '{button_text}'" finally: driver.quit()
This script opens the login page and waits explicitly for the login button to appear using two XPath locators:
contains(@class, 'login-btn') finds a button whose class attribute includes 'login-btn'.starts-with(@id, 'loginBtn') finds a button whose id attribute starts with 'loginBtn'.We use WebDriverWait with visibility_of_element_located to wait until the button is visible, avoiding unreliable fixed waits.
Assertions check that the button is visible, enabled, and has the exact text 'Log In'.
Finally, the driver quits to close the browser.
Now add data-driven testing with 3 different login button class names and id prefixes to verify the button presence and text for each case.
id attribute contains the text "submit" anywhere inside it?class attribute starts with "btn-"?//div[contains(text(), 'Error') and starts-with(@class, 'alert-')]
<div class="alert-danger">Error: Invalid input</div> <div class="alert-success">Success</div> <div class="message-error">Error occurred</div>
//button[contains(@id, 'save-')]
<a> elements where the href attribute starts with "https://" and the link text contains "Learn". Which XPath expression correctly does this?Pass the test and this pattern moves unknown