How to check a Radio button with Selenium WebDriver
Selenium Tutorial for Beginners

How to Check a Radio button with Selenium WebDriver

Continuing on our Selenium Beginner’s series, let’s see How to Check a Radio button with Selenium WebDriver using Java. Hope you have already gone through the previous tutorials…

#4. Common Page elements & User actions to automate
#5. How to enter value in ‘Textbox’ using Selenium WebDriver
#6. How to click a Button in Selenium WebDriver using Java
#7. How to Mouse Hover an element in Selenium WebDriver
#8. How to Select value from Drop down list in Selenium WebDriver

Here we will try to check a radio button – the ‘Gender’ options on Facebook.com login page.

Check a Radio button with Selenium WebDriver

Inspect the Element first

This can be done by using browser tools. In simple terms just right click on the element (Gender radio buttons) & select ‘Inspect Element’. Note down the ‘attribute-value’ pairs, in this case name, id & value.

<< THE CODE >>

The steps followed are,

  1. Open a browser
  2. Open the website URL & maximize the window
  3. Find the Gender radio button
  4. Check the ‘Male’ radio button

 

Open Browser & Application

The code till,

is to open the browser and application. For reference, please visit our earlier posts in the series.

Identify the Radio button & its options

Inspect Radio button Selenium WebDriver

Since a set of radio button will have multiple options to select, we need to make a list of WebElements using the property which is same for all the radio buttons – in this case ‘name=”sex”.

An element can be identified using different properties. Please note that we need to take a property that is same for all the radio buttons. For details on different element locators, click here… After identifying the radio buttons, we are saving it in the ‘GenderList’ instance of type ‘WebElement’ which is an in-built class available in Selenium. We need to import this class in order to create objects,

Check a Radio button with Selenium WebDriver

Since it’s a list of WebElements (multiple radio button options), we need to iterate through each one of it searching for the match to be checked. Here we have used the attribute ‘value’ to choose our correct option. You can use any of the available property ‘attribute-value’ pair.

Checking a radio button is no different than clicking on it – hence,

The alternatives

The commented code above shows some alternative ways to check a radio button with Selenium WebDriver. You can even click on the desired radio button option directly by identifying it using any of the methods available in Selenium WebDriver – id, name, xpath, etc.

The Result

Check a Radio button with Selenium WebDriver | Once you run this program it will open the browser >> open the Facebook URL >> Check the ‘Male’ radio button.

Save

Save

Save

Save

Leave a Reply

Your email address will not be published. Required fields are marked *