Monday, 1 August 2016

Selenium WebDriver Commands Using Python: Complete Tutorial with Examples

 


Introduction

Selenium WebDriver is one of the most widely used tools for automating web application testing. When combined with Python, it allows testers to write readable scripts that interact with web browsers and validate application functionality.

To develop effective automation scripts, it is important to understand the different Selenium WebDriver commands and how they work.

This tutorial covers essential Selenium WebDriver commands using Python, with practical examples covering browser operations, web elements, locators, dropdowns, alerts, frames, waits and keyboard interactions.

Whether you are a beginner or preparing for an Automation Test Engineer interview, these commands form an important foundation.

1. What Are Selenium WebDriver Commands?

Selenium WebDriver commands are methods and properties that allow automation scripts to control browser sessions and interact with web application elements.

They can be broadly classified into:

  • Browser commands.

  • Navigation commands.

  • Web element commands.

  • Locator strategies.

  • Dropdown and selection commands.

  • Alert handling commands.

  • Frame handling commands.

  • Window management commands.

  • Wait commands.

  • Keyboard and mouse interactions.

Understanding these categories helps testers write structured and maintainable automation scripts.

2. Browser Commands in Selenium Python

Browser commands are used to launch, manage and close browser sessions.

CommandDescription
webdriver.Chrome()Launches Chrome
webdriver.Firefox()Launches Firefox
driver.maximize_window()Maximises browser window
driver.minimize_window()Minimises browser window
driver.fullscreen_window()Enters fullscreen mode
driver.close()Closes the current window
driver.quit()Ends the WebDriver session

Example: Launching Chrome

from selenium import webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.get("https://www.google.com")

driver.quit()

The quit() method should generally be used when the test session is complete because it closes all windows associated with that WebDriver session.

3. Browser Navigation Commands

Navigation commands allow testers to move between web pages.

CommandPurpose
driver.get(url)Opens a URL
driver.back()Navigates to previous page
driver.forward()Navigates to next page
driver.refresh()Reloads current page

Example: Navigation Operations

from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.python.org")

driver.get("https://www.selenium.dev")

driver.back()

driver.forward()

driver.refresh()

driver.quit()

These commands are useful when testing browser navigation, redirects and application workflows.

4. Browser Information Commands

Selenium provides properties to retrieve information about the current browser page.

PropertyDescription
driver.titleReturns page title
driver.current_urlReturns current URL
driver.page_sourceReturns current page HTML
driver.current_window_handleReturns current window handle
driver.window_handlesReturns all open window handles

Example:

from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.selenium.dev")

print("Title:", driver.title)

print("URL:", driver.current_url)

print("Window:", driver.current_window_handle)

print("HTML:", driver.page_source[:500])

driver.quit()

The page_source property can help investigate page content, although it should not replace targeted element locators for normal test assertions.

5. Locating Web Elements in Selenium Python

Before interacting with a web element, Selenium must identify it.

The find_element() method locates a single matching element, while find_elements() returns a list of matching elements.

Common locator strategies include:

LocatorExample
IDBy.ID
NameBy.NAME
Class NameBy.CLASS_NAME
Tag NameBy.TAG_NAME
Link TextBy.LINK_TEXT
Partial Link TextBy.PARTIAL_LINK_TEXT
CSS SelectorBy.CSS_SELECTOR
XPathBy.XPATH

Example:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("https://www.saucedemo.com/")

username = driver.find_element(
    By.ID, "user-name"
)

password = driver.find_element(
    By.NAME, "password"
)

login_button = driver.find_element(
    By.ID, "login-button"
)

username.send_keys("standard_user")

password.send_keys("secret_sauce")

login_button.click()

driver.quit()

This example uses a public demonstration application. Use its published test credentials and verify their validity before running the script.

6. Web Element Commands

Web element commands allow testers to interact with individual elements.

Command or PropertyPurpose
click()Clicks an element
send_keys()Enters text
clear()Clears an input field
textRetrieves visible text
get_attribute()Retrieves an HTML attribute
is_displayed()Checks visibility
is_enabled()Checks whether enabled
is_selected()Checks selection state
tag_nameReturns element tag name
sizeReturns element dimensions
rectReturns element position and dimensions

Example: Web Element Interaction

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("https://www.saucedemo.com/")

username = driver.find_element(
    By.ID, "user-name"
)

print("Displayed:", username.is_displayed())

print("Enabled:", username.is_enabled())

username.send_keys("standard_user")

print("Value:", username.get_attribute("value"))

username.clear()

driver.quit()

These commands are useful for validating form fields, buttons, links and other interface components.

7. Handling Dropdowns Using Select Class

Selenium provides the Select class for standard HTML dropdown elements.

Example:

from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By

dropdown = Select(
    driver.find_element(By.ID, "country")
)

dropdown.select_by_visible_text("India")

dropdown.select_by_value("IN")

dropdown.select_by_index(1)

dropdown.deselect_all()

The deselect_all() method applies to multi-select dropdowns, not ordinary single-select dropdowns.

You can also retrieve available options:

options = dropdown.options

for option in options:
    print(option.text)

The Select class works with standard HTML select elements. Custom JavaScript dropdowns require normal element interactions.

8. Handling JavaScript Alerts

Selenium supports JavaScript alert, confirmation and prompt dialogs.

The switch_to.alert property provides access to the active alert.

CommandPurpose
driver.switch_to.alertSwitches to active alert
alert.accept()Accepts alert
alert.dismiss()Dismisses alert
alert.send_keys()Enters text into prompt
alert.textRetrieves alert message

Example:

alert = driver.switch_to.alert

print(alert.text)

alert.accept()

For a prompt:

alert = driver.switch_to.alert

alert.send_keys("Automation Testing")

alert.accept()

9. Handling Frames and iFrames

Web applications sometimes display content inside frames.

Selenium provides switch_to.frame() to interact with elements inside a frame.

Example:

from selenium.webdriver.common.by import By

driver.switch_to.frame("frameName")

driver.find_element(
    By.ID, "username"
).send_keys("tester")

driver.switch_to.default_content()

You can switch to a frame using its name, ID, WebElement or index.

To return to the parent frame:

driver.switch_to.parent_frame()

Always switch to the correct frame before locating elements inside it.

10. Handling Multiple Browser Windows

Some applications open new tabs or windows after a user clicks a link.

Selenium provides window handles to manage these sessions.

Example:

parent_window = driver.current_window_handle

# Perform an action that opens a new window

for window in driver.window_handles:

    if window != parent_window:

        driver.switch_to.window(window)

        print(driver.title)

driver.close()

driver.switch_to.window(parent_window)

This is useful when testing payment gateways, external links and multi-window workflows.

11. Synchronisation Commands: Implicit and Explicit Waits

Modern web applications often load elements asynchronously. Selenium scripts should wait for the required conditions rather than rely on fixed delays.

Implicit Wait

driver.implicitly_wait(10)

This sets a global wait for element location operations.

Explicit Wait

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 10)

element = wait.until(
    EC.visibility_of_element_located(
        (By.ID, "login-button")
    )
)

Common Expected Conditions

  • presence_of_element_located()

  • visibility_of_element_located()

  • element_to_be_clickable()

  • text_to_be_present_in_element()

  • invisibility_of_element_located()

  • alert_is_present()

Explicit waits are particularly useful for dynamic pages and AJAX-based applications.

Avoid mixing implicit and explicit waits because the combined waiting behaviour can become unpredictable.

12. Mouse and Keyboard Operations

Selenium provides the ActionChains class for advanced mouse and keyboard interactions.

Example: Mouse hover.

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By

menu = driver.find_element(
    By.ID, "menu"
)

actions = ActionChains(driver)

actions.move_to_element(menu).perform()

Example: Keyboard interaction.

from selenium.webdriver.common.keys import Keys

search = driver.find_element(
    By.NAME, "q"
)

search.send_keys("Selenium Python")

search.send_keys(Keys.ENTER)

ActionChains can also perform drag-and-drop, double-click, right-click and key combinations.

13. Screenshot Commands in Selenium Python

Screenshots are useful when investigating test failures.

Save a screenshot:

driver.save_screenshot("homepage.png")

Capture a screenshot through a WebElement:

element = driver.find_element(
    By.ID, "login-button"
)

element.screenshot("login_button.png")

In a professional framework, screenshots can be captured automatically when a test fails and attached to execution reports.

14. Practical Example: Automating a Login Workflow

The following example combines several Selenium commands into a single test.

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

driver = webdriver.Chrome()

try:

    driver.maximize_window()

    driver.get("https://www.saucedemo.com/")

    username = driver.find_element(
        By.ID, "user-name"
    )

    password = driver.find_element(
        By.ID, "password"
    )

    username.send_keys("standard_user")

    password.send_keys("secret_sauce")

    driver.find_element(
        By.ID, "login-button"
    ).click()

    wait = WebDriverWait(driver, 10)

    wait.until(
        EC.url_contains("inventory")
    )

    assert "inventory" in driver.current_url

    print("Login test passed")

finally:

    driver.quit()

This example demonstrates browser launch, navigation, element location, text entry, clicking, explicit waiting and assertion-based validation.

15. Best Practices for Using Selenium Commands

For maintainable automation scripts, follow these practices:

  1. Use stable locators wherever possible.

  2. Prefer explicit waits for dynamic elements.

  3. Avoid unnecessary time.sleep() statements.

  4. Keep browser setup and cleanup reusable.

  5. Use Page Object Model for larger projects.

  6. Avoid duplicating browser interaction code.

  7. Use meaningful assertions.

  8. Capture screenshots and logs for failures.

  9. Keep test data separate from test logic.

  10. Execute tests across supported browsers.

These practices help improve test reliability and reduce maintenance effort.

Selenium Python Training at Palium Skills

Palium Skills provides practical Automation Testing training for freshers, manual testers and working professionals.

The Selenium Python programme can cover:

  • Python programming fundamentals.

  • Selenium WebDriver installation.

  • Browser and navigation commands.

  • Web element interactions.

  • XPath and CSS selectors.

  • Dropdowns, alerts and frames.

  • Waits and dynamic elements.

  • PyTest framework.

  • Page Object Model.

  • Data-driven testing.

  • Automation framework development.

  • Reporting and real-time project implementation.

Classroom sessions are available at South Kolkata and Salt Lake centres, along with instructor-led live online sessions for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar, Near South City Mall, Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Enquire about Selenium with Python, Selenium with Java and Playwright Automation Testing training.

Frequently Asked Questions (FAQs)

1. What are Selenium WebDriver commands?

Selenium WebDriver commands are methods and properties used to control browsers, locate web elements, interact with applications and validate application behaviour.

2. What is the difference between find_element() and find_elements()?

find_element() returns the first matching WebElement and raises an exception if no match is found. find_elements() returns a list of matching elements, which may be empty.

3. What is the difference between close() and quit()?

close() closes the current browser window. quit() ends the WebDriver session and closes all associated windows.

4. How do you enter text in Selenium Python?

Use the send_keys() method on an input WebElement.

5. How do you retrieve text from a web element?

Use the text property of the WebElement.

6. How do you handle alerts in Selenium Python?

Use driver.switch_to.alert and then call accept(), dismiss() or send_keys() as appropriate.

7. Which wait is recommended in Selenium Python?

Explicit waits are often recommended for waiting for specific application conditions. They provide more control than fixed delays.

8. Can Selenium Python automate mouse movements?

Yes. The ActionChains class supports mouse hover, drag-and-drop, double-click and other advanced interactions.


Conclusion

Selenium WebDriver commands are the building blocks of browser automation using Python. Understanding browser operations, navigation, locators, web element interactions, waits, alerts and frames helps testers develop effective automation scripts.

Once you become comfortable with these commands, the next step is to combine them with PyTest, Page Object Model and reusable framework components to build professional automation solutions.

TDS on Salary: A Practical Guide for HR and Payroll Professionals

  TDS on Salary: A Complete Guide for HR and Payroll Professionals Learn how TDS on salary works in India , the role of employers, employee...