Test Overview
This test opens a web page, finds an element using its ID, clicks it, and verifies the expected page change.
This test opens a web page, finds an element using its ID, clicks it, and verifies the expected page change.
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 import unittest class TestFindElementByID(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get('https://example.com') def test_click_button_by_id(self): driver = self.driver # Wait until the button with ID 'submit-btn' is present button = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'submit-btn')) ) button.click() # Verify the URL changed to expected page WebDriverWait(driver, 10).until( EC.url_contains('submit-success') ) self.assertIn('submit-success', driver.current_url) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser window is open at 'https://example.com' | — | PASS |
| 2 | Wait until element with ID 'submit-btn' is present | Page loaded with a button having ID 'submit-btn' | Element with ID 'submit-btn' is found | PASS |
| 3 | Click the button with ID 'submit-btn' | Button clicked, page starts navigation | — | PASS |
| 4 | Wait until URL contains 'submit-success' | Browser URL changes to include 'submit-success' | Current URL contains 'submit-success' | PASS |
| 5 | Test ends and browser closes | Browser window closed | — | PASS |
find_element(By.ID, "id") with the By class.By.ID for ID locator [OK]By.ID in Selenium Python?By class is located in selenium.webdriver.common.by module.By. import selenium.webdriver.By as By uses invalid syntax. from selenium.webdriver.common.by import ID tries to import ID which doesn't exist. from selenium.webdriver import By imports By from wrong module.By from common.by [OK]from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() element = driver.find_element(By.ID, "submit-btn") print(element.tag_name)
find_element returns the WebElement object.element.tag_name returnstag_name attribute returns the HTML tag name of the found element, e.g., 'button' or 'input'.from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() element = driver.find_element(By.id, "username")
By class attributes are uppercase, so it should be By.ID not By.id.webdriver.Chrome() are present. The method find_element with By.ID is correct syntax.NoSuchElementException. To avoid test failure, catch this exception.Pass the test and this pattern moves unknown