Wednesday, 1 June 2016

Handling Web Elements Using Selenium Python: Buttons, Text Boxes, Checkboxes and Radio Buttons


Introduction

Web applications contain different types of interactive elements, including text boxes, buttons, checkboxes, radio buttons, dropdowns, links and file-upload fields. Automating these elements is one of the most important skills required by a software automation tester.

Selenium WebDriver provides several methods to locate and interact with these elements using Python. Understanding these methods helps testers develop reliable automation scripts for login pages, registration forms, shopping websites, booking applications and enterprise systems.

In this tutorial, we will explore how to identify, validate and interact with commonly used web elements using Selenium Python.

1. Understanding Web Elements in Selenium

A web element is an HTML component displayed on a web page. Selenium represents an individual element through the WebElement interface.

For example, consider the following HTML:

<input type="text" id="username" placeholder="Enter username">

<button id="login">Login</button>

<input type="checkbox" id="remember">

<input type="radio" name="gender" value="male">

Selenium can locate these elements using attributes such as ID, name, class name, CSS selector and XPath.

The following Python code demonstrates a basic element search:

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

driver = webdriver.Chrome()
driver.get("https://example.com")

element = driver.find_element(By.ID, "username")
print(element)

Replace the example URL and locator with those belonging to your application.

2. Handling Text Boxes Using Selenium Python

Text boxes are commonly used for entering usernames, passwords, email addresses, search terms and other information.

Important methods include:

  • send_keys() – enters text.

  • clear() – removes existing text.

  • get_attribute() – retrieves an HTML attribute.

  • is_displayed() – checks whether an element is visible.

  • is_enabled() – checks whether an element is enabled.

Example: Entering text into a username field

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

driver = webdriver.Chrome()
driver.get("https://example.com/login")

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

if username.is_displayed() and username.is_enabled():
    username.clear()
    username.send_keys("testuser")

print(username.get_attribute("value"))

driver.quit()

The clear() method is useful when a field already contains text.

For password fields, Selenium uses the same send_keys() method:

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

Avoid printing or logging actual passwords in real automation projects.

3. Handling Buttons Using Selenium Python

Buttons are used to submit forms, log in, search, save information and navigate through application workflows.

Selenium uses the click() method to interact with buttons.

from selenium.webdriver.common.by import By

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

if login_button.is_displayed() and login_button.is_enabled():
    login_button.click()

For dynamic applications, use an explicit wait instead of clicking immediately.

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)

login_button = wait.until(
    EC.element_to_be_clickable((By.ID, "login"))
)

login_button.click()

This approach waits until the button is clickable, reducing failures caused by page loading delays.

4. Handling Checkboxes

Checkboxes allow users to select one or more options. Examples include accepting terms and conditions, selecting preferences and choosing multiple products.

The is_selected() method checks whether a checkbox is already selected.

Example: Selecting a checkbox only when necessary

checkbox = driver.find_element(By.ID, "terms")

if not checkbox.is_selected():
    checkbox.click()

print(checkbox.is_selected())

This is better than clicking a checkbox unconditionally because clicking an already-selected checkbox will deselect it.

Handling multiple checkboxes

checkboxes = driver.find_elements(
    By.CLASS_NAME, "interest"
)

for checkbox in checkboxes:
    if checkbox.is_displayed() and checkbox.is_enabled():
        if not checkbox.is_selected():
            checkbox.click()

This example assumes that all matching checkboxes should be selected. In a real application, apply business rules to select only the required options.

5. Handling Radio Buttons

Radio buttons allow users to select one option from a group.

For example, a registration form may provide options such as:

  • Male

  • Female

  • Other

Radio buttons belonging to the same group generally share the same name attribute.

Example: Selecting a radio button

male_radio = driver.find_element(
    By.XPATH,
    "//input[@name='gender' and @value='male']"
)

if not male_radio.is_selected():
    male_radio.click()

To verify the selection:

print(male_radio.is_selected())

When selecting another radio button in the same group, the browser normally deselects the previously selected option automatically.

6. Handling Dropdown Lists

Dropdowns are frequently used for selecting countries, cities, categories and other predefined values.

Selenium provides the Select class for standard HTML <select> elements.

from selenium.webdriver.support.ui import Select

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

country_dropdown.select_by_visible_text("India")

Other useful methods include:

country_dropdown.select_by_value("IN")

country_dropdown.select_by_index(1)

You can retrieve the selected option:

selected_option = country_dropdown.first_selected_option

print(selected_option.text)

Important: The Select class works only with native HTML <select> elements. Custom dropdowns built using JavaScript, React or other frontend frameworks generally require normal Selenium element interactions.

7. Handling Links and Images

Selenium can also identify hyperlinks and image elements.

Clicking a hyperlink:

link = driver.find_element(
    By.LINK_TEXT, "Contact Us"
)

link.click()

Checking an image:

image = driver.find_element(
    By.ID, "companyLogo"
)

print(image.is_displayed())
print(image.get_attribute("src"))

These techniques are useful when testing navigation menus, logos, banners and image-based components.

8. Handling File Uploads

Many applications allow users to upload documents, photographs, resumes and other files.

For a standard HTML file input, Selenium can upload a file using send_keys().

upload = driver.find_element(
    By.ID, "fileUpload"
)

upload.send_keys(
    r"C:\Users\Test\Documents\resume.pdf"
)

The file path must point to an existing file accessible to the machine running the browser session.

For remote execution, the file may need to be transferred to the remote browser environment using the supported file-upload mechanism.

9. Handling Disabled and Hidden Elements

Automation testers must verify whether elements are visible and enabled before interacting with them.

Selenium provides three useful methods:

MethodPurpose
is_displayed()Checks whether the element is visible
is_enabled()Checks whether the element is enabled
is_selected()Checks whether a checkbox or radio button is selected

Example:

button = driver.find_element(By.ID, "submit")

print("Visible:", button.is_displayed())
print("Enabled:", button.is_enabled())

A hidden element may exist in the HTML document but not be visible to the user. Selenium normally cannot interact with such an element through a regular user action.

Automation scripts should generally test the application as a user would rather than relying on JavaScript to bypass visibility or interaction restrictions.

10. Practical Example: Automating a Registration Form

The following example combines text boxes, radio buttons, checkboxes and a submit button.

The locators are illustrative. Replace them with the actual IDs and attributes of your practice application.

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()
wait = WebDriverWait(driver, 10)

try:
    driver.get("https://example.com/register")

    # Enter name
    name = wait.until(
        EC.visibility_of_element_located(
            (By.ID, "name")
        )
    )
    name.send_keys("Test User")

    # Enter email
    email = driver.find_element(By.ID, "email")
    email.send_keys("test@example.com")

    # Select gender
    gender = driver.find_element(
        By.XPATH,
        "//input[@name='gender' and @value='male']"
    )

    if not gender.is_selected():
        gender.click()

    # Accept terms
    terms = driver.find_element(By.ID, "terms")

    if not terms.is_selected():
        terms.click()

    # Submit form
    submit = wait.until(
        EC.element_to_be_clickable(
            (By.ID, "submit")
        )
    )
    submit.click()

finally:
    driver.quit()

This example demonstrates how multiple web elements can be handled within a single automation workflow.

11. Best Practices for Handling Web Elements

Follow these recommendations when developing Selenium Python scripts:

  1. Prefer stable IDs and meaningful attributes when locating elements.

  2. Use CSS selectors or XPath when other locator strategies are unsuitable.

  3. Use explicit waits for dynamically loaded elements.

  4. Check whether checkboxes and radio buttons are already selected.

  5. Verify that buttons are enabled before clicking.

  6. Avoid unnecessary time.sleep() statements.

  7. Use find_elements() when multiple matching elements are expected.

  8. Keep locators organised in Page Object Model classes.

  9. Use meaningful variable names and reusable methods.

  10. Always close the browser session using driver.quit().

These practices improve script reliability and make automation frameworks easier to maintain.

12. Career Opportunities in Selenium Python Automation Testing

Knowledge of web element handling is an essential foundation for automation testing careers.

After learning these concepts, learners can progress towards:

  • Selenium Python automation frameworks.

  • PyTest-based test automation.

  • Page Object Model implementation.

  • Data-driven automation testing.

  • API testing and integration testing.

  • Continuous integration using Jenkins or GitHub Actions.

  • SDET and Automation Test Engineer roles.

Practical experience with real-world testing scenarios is particularly valuable during technical interviews.

Learn Selenium Python Automation Testing with Palium Skills

Palium Skills offers practical Automation Testing training designed for freshers, graduates, manual testers and working professionals.

The learning pathway can include:

  • Python programming fundamentals.

  • Selenium WebDriver with Python.

  • Locators and web element handling.

  • Explicit waits and dynamic elements.

  • PyTest framework.

  • Page Object Model and framework development.

  • Data-driven testing.

  • Real-time automation projects.

  • Interview preparation and practical exercises.

Training modes include classroom sessions at South Kolkata and Salt Lake, Kolkata, as well as 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.

Frequently Asked Questions

1. How do I enter text into a textbox using Selenium Python?

Use the send_keys() method on the located WebElement.

2. How do I click a button using Selenium Python?

Locate the button using an appropriate locator and call its click() method. An explicit wait is recommended for dynamic applications.

3. How can I check whether a checkbox is selected?

Use the is_selected() method. It returns True if the checkbox is selected.

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

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

5. Can Selenium handle dropdowns in Python?

Yes. Selenium's Select class handles standard HTML dropdowns. Custom dropdowns require a different interaction approach.

6. Can Selenium Python upload files?

Yes. For standard file input elements, use send_keys() with the full path of the file.

7. Is Selenium Python suitable for beginners?

Yes. Python's readable syntax makes it a suitable language for learning Selenium automation testing, provided learners also understand basic programming and web technologies.

No comments:

Post a Comment

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...