How to Handle Radio Buttons in Selenium WebDriver

Paulo Oliveira

Posted On: March 22, 2024

view count71599 Views

Read time20 Min Read

Radio buttons are a significant component within web forms, allowing users to make singular selections from a predefined array of options. Unlike checkboxes, radio buttons confine users to selecting only one choice from within a designated group of alternatives. This inherent quality renders them particularly advantageous for situations necessitating distinct choices, such as gender specifications, binary determinations, or category preferences.

In Selenium WebDriver, effectively handling radio buttons ensures accurate user interactions during automated testing. Mastering the techniques for handling radio buttons in Selenium enhances the reliability of test scripts and ensures comprehensive test coverage across various web applications and scenarios.

In this Selenium Python tutorial on handling radio buttons in Selenium, we will learn different ways to locate radio buttons and how to handle them.

Significance of Radio Buttons in Web Forms

Web forms serve as the digital gateway for users to engage with online services, from creating accounts to purchasing. Within these forms, radio buttons find their niche as they streamline the process of capturing user preferences. However, misusing these elements can result in data inaccuracies, functional glitches, or misleading test outcomes, particularly in automated testing.

Therefore, QA professionals must acquire the skills and knowledge to work with radio buttons.

Getting Started with Handling Radio Buttons in Selenium

We will automate the use of radio buttons on two web pages: Radio button Demo page on the LambdaTest Selenium Playground and a page built explicitly for this blog, which is available on my GitHub.

Preparing the Environment

To start exploring radio buttons, preparing the required environment for our demonstrations is essential. In this blog, we will use Python, one of the most popular programming languages, Selenium WebDriver, a versatile tool for automating web browser interactions, pytest plugin, a framework for writing tests in Python, and a suitable IDE to develop Python scripts. We will run our test on the LambdaTest platform.

LambdaTest is an AI-powered test orchestration and execution platform for running manual and automated tests at scale. The platform allows you to perform real-time and automation testing across 3000+ environments and real mobile devices.

Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around Selenium, Playwright, Cypress, and more.

To be able to run the code of this blog, ensure that you have the following elements in place:

Python

Verify that Python is installed on your system. If Python isn’t already set up on your machine, navigate to Python’s official website. Search for the version tailored to your OS and proceed with the guided setup. During this phase, ensure you opt to “Include Python in PATH” for effortless accessibility via the terminal or command interface.

Selenium WebDriver and pytest Libraries

Once Python is installed, use the Python package manager, pip, to install Selenium and pytest by just running the following command:

Requirements.txt contains the dependencies that we want to install.

Requirements.txt contains

After running, you can see the below output:

output

IDE

Select a suitable code editor or Integrated Development Environment (IDE) like Visual Studio Code or PyCharm to develop your Python scripts. In this blog, we recommend Visual Studio Code for its user-friendly interface and robust features.

LambdaTest Capabilities

To perform Selenium Python testing on the LambdaTest cloud grid, you should use the capabilities to configure the environment where the test will run. In this blog, we will perform Python automation testing on Windows 11 and Chrome.

Ensure you have the LambdaTest capabilities code ready to be integrated into your test script.

You can generate the capabilities code from the LambdaTest Capabilities Generator.

Then, you should get the “Username” and “Access Key” from your LambdaTest Profile Section > Password & Security and set them as environment variables.

environment variables

Configuration Files

To run the code shown in this blog, you need two files in the project’s root folder: config.ini and conftest.py. Python configuration files are essential for configuring the Selenium WebDriver for our automation tests and ensuring seamless integration with the LambdaTest cloud grid.

config.ini

The config.ini file serves as a configuration file that houses crucial parameters and settings required for our Selenium automation script.

It is divided into three sections, each serving a specific purpose:

[WEBSITE]: The [WEBSITE] section specifies the web page URL we intend to test.

[CLOUDGRID]: The [CLOUDGRID] section configures our interaction with the LambdaTest cloud grid. It includes details such as the grid URL (grid_url), build name (build_name), test name (test_name), and other capabilities such as browser version, Selenium version, and visual testing settings.

[ENV]: The [ENV] section defines the platform (platform) and browser (browser_name) configurations for our tests.

These configurations in config.ini centralize necessary settings, making it easier to modify test parameters when needed without changing the core code. It promotes code maintainability and reusability across different test cases.

conftest.py

The conftest.py file sets up fixtures and configurations shared across multiple test cases. It plays a crucial role in initializing the WebDriver for our Selenium tests.

github

Here’s a breakdown of its key components:

key components

It imports essential modules like pytest, webdriver from Selenium, os, and configparser for handling configurations.

configuration file

The config.ini file is read using the configparser module to retrieve values such as LambdaTest username, access key, grid URL, platform, browser name, and other capabilities required for the test configuration.

pytest fixture

It sets up WebDriver options, including LambdaTest-specific capabilities, by creating a dictionary named lt_options. These options ensure that our tests run on LambdaTest’s cloud infrastructure with the specified configurations.

specified configuration

It then builds the URL to connect to the LambdaTest hub with the appropriate username, access key, and grid URL. The WebDriver instance is created using webdriver.Remote() by passing the command_executor (the LambdaTest hub URL) and the options with desired capabilities.

The yield driver statement allows the test functions using this fixture to access the WebDriver instance and use it for testing. After completing the test function(s), the fixture will execute the driver.quit statement to close the WebDriver and release any associated resources.

Once you have met these basic prerequisites, you will be well-prepared to explore radio buttons in Selenium WebDriver using Python and LambdaTest.

Locating Radio Buttons in Selenium WebDriver

In this section, we will start looking into how to locate radio buttons in Selenium within the intricate web of HTML structures. Understanding these techniques is akin to unlocking the secrets of web automation, where precision is essential.

Let’s explore the methods of revealing and interacting with the radio buttons in Selenium.

Using ID

The unique fingerprint, known as the ‘id’ attribute of an HTML element, grants it an unmistakable identity among the web page’s elements tree. The ‘id’ attribute has formidable precision and is a pathway to radio button location without compromise. Through the unique ‘id’ attribute, the path to accessing a radio button unfolds with surgical precision.

Taking a look at the element structure of the page, we can see:

page structure

Considering that we want to locate the stg environment radio button using ID, we can do it as shown below:

Using Name Attribute

In the web’s elements set, the ‘name’ attribute allows elements to be organized into thematic groups. This allows the radio buttons to share a common name, enabling their pinpoint location.

Taking a look at the element structure of the page, we can see:

name attribute

Considering that we want to locate the Female radio button using the NAME attribute, we can do it as shown below:

Using XPath

In web automation, XPath emerges as a tool that walks inside the architecture of HTML, arriving at the radio buttons with precision. When the attributes of other elements falter, XPath’s navigation steps in.

Taking a look at the element structure of the page, we can see:

Using XPath

Considering that we want to locate the Male radio button using XPATH, we can do it as shown below:

Using CSS Selectors

Cascading Style Sheets (CSS) Selectors, with their conciseness, waltz into the limelight. They provide a deft and elegant means of singling out elements based on a tapestry of attributes, classes, or structures. CSS Selectors master the art of discerning radio buttons by their intrinsic attributes, painting a portrait of precision.

Taking a look at the element structure of the page, we can see:

selectors

Considering that we want to locate the Female radio button using CSS_SELECTOR, we can do it as shown below:

Info Note

Automate Selenium Python tests on the cloud. Try LambdaTest Today!

Interacting with Radio Buttons in Selenium

Now that we have honed our skills in locating radio buttons in Selenium let’s delve into their practical use. This section will explore the hands-on aspect of working with radio buttons, focusing on the core action of clicking.

Clicking on radio buttons

Clicking a radio button is the primary way users make selections, and when it comes to automating interactions, it’s very important and essential. To emulate a user’s click on a radio button in Selenium and Python, simply call the click() method on the element object you’ve obtained during the locating step.

Below are four illustrative examples employing Python and Selenium, one for each different locator strategy explored in the previous section:

Test Case 1: Locate the Radio Button by ID and Click

This first script aims to automate web page interactions with radio buttons. It begins by navigating to the specific web page hosted at https://paulocoliveira.github.io/mypages/radiobuttons.html. Once on the page, the script uses the ID to precisely locate a radio button element with an ID equal to “stg-env” and then clicks on it using the click() method.

Test Case 2: Locate the Radio Button by Name and Click

This second script aims to automate interactions with radio buttons on another webpage. It begins by navigating the “radio button demo” page hosted at https://www.lambdatest.com/selenium-playground/radiobutton-demo. Once on the page, the script uses the NAME attribute to precisely locate the radio button elements with the value attribute equal to “optradio” but with the index=1. Then, it clicks on the radio button using the click() method.

Test Case 3: Locate the Radio Button by XPath and Click

The aim of this third script is to automate interactions with radio buttons on the same web page. It navigates to the webpage, uses the XPATH to locate the radio button input with the value attribute equal to “Male”, and then clicks on it using the click() method.

Test Case 4: Locate the Radio Button by CSS Selector and Click

Finally, the last script goal aims to automate radio button interactions on the same web page. It navigates to the web page, uses the CSS_SELECTOR to locate a radio button input with the value attribute equal to “Female”, and then clicks on it using the click() method.

You can run the four tests by running the below command:

pytest

These test cases serve as instructive demonstrations of the methodologies for locating radio buttons using ID, Name, XPath, and CSS. Still, they underscore the seamless interaction achievable by executing click actions on these radio buttons.

Checking the Radio Buttons State in Selenium

When it comes to automated testing involving radio buttons, one must assess their various states to guarantee test accuracy and adaptability. In this section, we’ll examine radio button states using Python and Selenium.

Checking if a radio button is being displayed

Checking whether a radio button is visible on a webpage is paramount. Selenium equips us with the is_displayed() method to determine the visibility status of an element. For instance, let’s investigate whether the “Male” radio button is visible on a sample page:

This code navigates to a webpage and verifies if the “Male” radio button is being displayed, facilitating decision-making based on its visibility.

In the above sample, if the button is displayed, we print a message informing it and click the option. If not, we just print a message informing you of the status.

Validating if a radio button is accessible

Determining whether a radio button is active or inactive can be achieved through the is_enabled() method. This is especially interesting when handling radio buttons that dynamically alter their availability. For instance, to confirm the enabled status of a radio button with the value = “RadioButton3”:

This snippet identifies a radio button with the specified value and validates its active or inactive state, enabling you to tailor your test logic accordingly.

In the above case, if the button is enabled or disabled, the code is just printing the status. However, actions can be triggered depending on the status.

Verifying if a radio button is being selected

Lastly, as radio buttons are designed for exclusive choices, we employ the is_selected() method to ascertain whether a radio button is chosen. For instance, after clicking the “Male” radio button, we can confirm its selection status:

In this script, we first locate and click the “Male” radio button, then verify its selection status. This step is vital for ensuring that user selections align with expected outcomes.

In the above case, whether the button is selected or not, the code just prints the status; however, again, actions can be executed depending on the status.

You can run these three tests by running the below command:

You will get this result:

test result

By adeptly assessing these radio button states, you can ensure the accuracy and dependability of your automated tests, confirming that your web applications work as intended in diverse scenarios.

Advanced Use Cases for Handling Radio Buttons in Selenium

Navigating hidden radio buttons is vital in web automation, particularly when dealing with hidden elements when a page loads. In this section, we’ll delve into techniques for working with these radio buttons in Selenium using Python.

Handling initially hidden radio buttons in Selenium

On certain web pages, radio buttons may remain hidden when the page first loads, rendering direct interaction impossible and potentially leading to script failures. To address this challenge, we employ explicit waits to ensure the element becomes visible before interacting with it.

In this code, we first navigate to a sample web page featuring a hidden radio button. To ensure the document is fully loaded, we implement an explicit wait (document.readyState == ‘complete’). We then locate the hidden radio button by its ID and attempt to click it. If the element is not visible when clicking, the script will fail. That is what is going to happen when executing this script.

Revealing hidden radio buttons in Selenium

You can make hidden elements visible in some scenarios by performing specific actions on the web page. In such cases, we first trigger the element’s visibility and then interact with it.

This script revisits the same web page featuring a hidden radio button. After ensuring the document is fully loaded with an explicit wait, we locate and click a toggle button with the ID “toggle-hidden.” This action reveals the previously hidden radio button, allowing us to interact with it, locate it, and click on it.

You can run these two tests by running the below command:

You will get this result:

result

test result two

test result final

By mastering these techniques, you can confidently navigate hidden radio buttons in Selenium and handle web automation scenarios gracefully.

Retrieving radio buttons value in Selenium

When it comes to automating interactions involving radio buttons, there are occasions where you need to extract the value of the option that’s currently selected. In this section, we’ll achieve this goal using Python and Selenium.

We start by navigating to a sample web page containing radio buttons in the provided code. These radio buttons share a common ‘name’ attribute, “optradio.” To demonstrate the process of extracting the selected value, we choose the “Female” option through a simulated click action (corresponding to index 1 in the radio_buttons list).

Subsequently, we establish a variable known as selected_option to hold the value of the selected option. We then iterate through the radio buttons using a loop. We check each radio button’s selected status using the is_selected() method. If a radio button is found to be selected, we extract its value attribute using get_attribute(“value”) and store it in selected_option. The loop finishes as soon as a selected radio button is encountered.

You can run the above test by running the below command:

You will get this result:

radio buttons

Finally, we ensure whether a selected option was successfully identified. If so, we print the selected option; otherwise, we indicate that no option is currently selected. This method empowers you to extract and work with the value of the currently selected radio button in your Selenium automation scripts.

Conclusion

In this blog, we’ve explored handling radio buttons in Selenium using Python. We’ve covered key aspects, from locating radio buttons using various strategies, such as IDs, Names, XPath, and CSS Selectors, to interacting with them through simulated clicks.

Additionally, we’ve discussed verifying radio button states, including checking if they’re displayed, enabled, or selected, and addressing handling special cases like hidden radio buttons, offering effective solutions for such scenarios. Finally, we’ve demonstrated extracting the selected value from a group of radio buttons, a common requirement in test automation for ensuring the accuracy and reliability of your automation scripts in web application testing.

Mastering radio button automation is crucial for testers to enhance the quality and functionality of web applications, equipping them with the skills to create robust and effective automation scripts.

Frequently Asked Questions (FAQs)

What is a radio button in Selenium?

The Testing Pyramid is a framework that can assist both developers and quality assurance professionals to create high-quality software. It shortens developers’ time to determine whether a change they made breaks the code. It can also aid in the development of a more dependable test suite.

How to write XPath for radio buttons?

To write XPath for radio buttons in Selenium, you can follow these general steps:

  1. Inspect the Radio Button Element: Use browser developer tools to inspect the radio button element for which you want to create the XPath.
  2. Identify Unique Attributes: Look for unique attributes of the radio button element that can be used to create a specific XPath. Common attributes include “id”, “name”, “value”, or other custom attributes.
  3. Construct XPath: Based on the unique attributes identified, construct an XPath expression that accurately targets the desired radio button element. Here are a few examples:
    • XPath by ID: //input[@id=’radioButtonId’]
    • XPath by Name: //input[@name=’radioButtonName’]
    • XPath by Value: //input[@value=’optionValue’]
  4. Test XPath: Once you’ve constructed it, you can test it in the browser developer console or your Selenium script to ensure it correctly selects the radio button element.
  5. Handle Dynamic Elements: If radio button attributes are dynamic or subject to change, consider using more flexible XPath expressions or axes to target the element accurately under varying conditions.

By following these steps, you can create XPath expressions to effectively locate and interact with radio buttons in Selenium test automation.

What is the difference between a radio and a checkbox button in Selenium?

In Selenium, radio buttons and checkboxes are elements commonly used during web automation testing, but they serve different purposes.

A radio button typically represents a set of mutually exclusive options where only one option can be selected. When one radio button in a group is selected, any previously selected radio button in the same group is deselected automatically.

On the other hand, checkboxes enable multiple selections from a list of options. Users can select one or more checkboxes independently of each other.

In terms of Selenium automation, interacting with radio buttons involves selecting one option from a group using the click() method, ensuring only one option is selected at a time. For checkboxes, automation may involve checking or unchecking them using the click() method to reflect the desired selection state.

Understanding these differences is crucial for accurately automating interactions with these elements during web testing.

Author Profile Author Profile Author Profile

Author’s Profile

Paulo Oliveira

Paulo is a Quality Assurance Engineer with more than 15 years of experience in Software Testing. He loves to automate tests for all kind of applications (both backend and frontend) in order to improve the team’s workflow, product quality, and customer satisfaction. Even though his main roles were hands-on testing applications, he also worked as QA Lead, planning and coordinating activities, as well as coaching and contributing to team member’s development. Sharing knowledge and mentoring people to achieve their goals make his eyes shine.

Blogs: 15



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free