These are the most commonly used Selenium methods for locating HTML elements.
find_element(by, value)
β Returns one WebElementfind_elements(by, value)
β Returns a list of WebElementsfrom selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://example.com")
# Single element
username_input = driver.find_element(By.ID, "username")
# Multiple elements
all_links = driver.find_elements(By.TAG_NAME, "a")
You canβt interact with a page unless you can locate the HTML element.
click()
β Simulates a mouse clicksend_keys()
β Types into an input box.text
β Gets the visible text of an elementget_attribute()
β Gets the value of any HTML attributeusername_input.send_keys("admin")
login_button = driver.find_element(By.ID, "submit")
login_button.click()
click()
to select:
radio = driver.find_element(By.ID, "genderMale")
radio.click()
Check if selected:
is_selected = radio.is_selected()
Use the Select
class.
from selenium.webdriver.support.ui import Select
dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_visible_text("India")
alert = driver.switch_to.alert
print(alert.text)
alert.accept() # or alert.dismiss()
original = driver.current_window_handle
all_windows = driver.window_handles
driver.switch_to.window(all_windows[1]) # Go to new tab
driver.switch_to.window(original) # Come back
driver.switch_to.frame("frameName")
# Interact inside the frame
driver.switch_to.default_content() # Exit frame
driver.get("https://google.com")
driver.back()
driver.forward()
driver.refresh()
print(driver.current_url)
print(driver.title)
driver.implicitly_wait(10)
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "username")))
driver.execute_script("alert('Hello from JS!')")
Used when:
driver.save_screenshot("screenshot.png")
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
element = driver.find_element(By.ID, "hoverMenu")
actions.move_to_element(element).perform() # Hover
actions.context_click(element).perform() # Right click
# Drag and Drop
source = driver.find_element(By.ID, "dragMe")
target = driver.find_element(By.ID, "dropHere")
actions.drag_and_drop(source, target).perform()
# Get cookies
print(driver.get_cookies())
# Add cookie
driver.add_cookie({'name': 'mycookie', 'value': '123456'})
# Delete cookies
driver.delete_all_cookies()
Topic | Key Methods |
---|---|
Web Elements | find_element, click(), send_keys() |
Dropdowns | Select class |
Alerts | switch_to.alert |
Windows/Tabs | switch_to.window() |
Frames | switch_to.frame() |
Waits | implicitly_wait(), WebDriverWait |
JavaScript | execute_script() |
Screenshots | save_screenshot() |
ActionChains | move_to_element(), context_click(), drag_and_drop() |
Cookies | get_cookies(), add_cookie(), delete_all_cookies() |