Selenium WebDriver
Selenium WebDriver
1. ID Locator
Python
driver.find_element(By.ID, "username")
2. Name Locator
Python
driver.find_element(By.NAME, "email")
python
CopyEdit
driver.find_element(By.CLASS_NAME, "btn-primary")
python
CopyEdit
driver.find_element(By.TAG_NAME, "h1")
Python
python
CopyEdit
driver.find_element(By.PARTIAL_LINK_TEXT, "Sign")
7. CSS Selector
Examples:
Python
# ID
driver.find_element(By.CSS_SELECTOR, "#login")
# Class
driver.find_element(By.CSS_SELECTOR, ".btn")
# Attribute
driver.find_element(By.CSS_SELECTOR, "input[name='username']")
# Tag + class
driver.find_element(By.CSS_SELECTOR, "button.submit-btn")
8. XPath
Python
driver.find_element(By.XPATH, "/html/body/div[1]/form/input")
Python
driver.find_element(By.XPATH, "//input[@id='username']")
Other Examples:
python
CopyEdit
# Using text()
driver.find_element(By.XPATH, "//button[text()='Login']")
# Contains
driver.find_element(By.XPATH, "//a[contains(text(),'Sign')]")
# And condition
driver.execute_script("return document.getElementById('email')")
Python
driver.find_element(By.CSS_SELECTOR, "[data-test='submit-btn']")
driver.find_element(By.XPATH, "//*[@aria-label='Close']").
📌 Summary Table
Locator When to
Method Example
Type Use
Best, if
ID By.ID "username"
unique
If no unique
Name By.NAME "email"
ID
Class If class is
By.CLASS_NAME "btn-primary"
Name unique
Tag For
By.TAG_NAME "input"
Name lists/tables
Exact match
Link Text By.LINK_TEXT "Login"
for links
Powerful,
XPath By.XPATH "//input[@id='username']" use when
others fail
Rare,
"document.getElementById('e
JS/DOM execute_script() advanced
mail')"
usage
custom/test-
Attribute
data-* id='123']" friendly
s
locators
✅ Best Practices
Prefer ID > Name > CSS Selector > XPath (in that order).
Don’t rely on class names that change often (e.g., dynamic React
classes).
You can:
html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<label for="username">Username:</label>
<label for="password">Password:</label>
</form>
</div>
<ul id="user-list">
<li class="user">Alice</li>
<li class="user">Bob</li>
<li class="user">Charlie</li>
</ul>
</div>
<footer class="footer" data-role="site-footer">
<p>Contact: support@example.com</p>
</footer>
</body>
</html>
<form
By.NAME, By.TAG_NAME, By.ID
name="loginForm">
<input
By.ID, By.NAME, By.CSS_SELECTOR
id="username">
By.ID, By.LINK_TEXT,
<a id="forgot-link">
By.PARTIAL_LINK_TEXT
By.CLASS_NAME, By.CSS_SELECTOR,
<li class="user">
By.XPATH
python
CopyEdit
# By ID
driver.find_element(By.ID, "username")
# By Name
driver.find_element(By.NAME, "user")
# By Class Name
driver.find_element(By.CLASS_NAME, "btn")
# By Tag Name
driver.find_elements(By.TAG_NAME, "li")
# By Link Text
driver.find_element(By.PARTIAL_LINK_TEXT, "Forgot")
# By CSS Selector
driver.find_element(By.CSS_SELECTOR, "input[name='user']")
# By XPath
driver.find_element(By.XPATH, "//button[@data-test='submit-btn']")