How to handle radio button in selenium

Handling radio button

How to handle radio button in selenium

In this tutorial we will see how to handle radio button in selenium.

When you try to work on radio button first you need to understand you can opt only one option. If you have two options, you can select only one.

Let’s understand how radio button looks like in HTML. Check below snapshot.

Radio button html

When html page is designed with type as “radio” then radio button will be created it will be reflected as one option to select radio button in a web page. Please look below snapshot.

Radio Button

In selenium webdriver you can handle radio button using click method. Let’s see step wise

Step 1: Inspect the element and find the unique element (Xpath).

Step 2: Find the element and use click method.

Step 3: Validate the whether you have clicked or not using automation.

Step 1: Inspect the element and find the unique element (Xpath).

Xpath: //input[@value=’male’]

After finding Xpath you need to make sure 3 things whether you have written valid Xpath, Element is highlighted and having unique (1 of 1 node in html). Please look below screenshot.

RadioButtonXpath

Step 2: Find the element and use click method.

In above expression click is method to handle radio button using selenium webdriver.

Step 3: Validate the whether you have clicked or not using automation.

This is main thing we need to consider for every interview or real time as we need to cross check whether we have clicked or not? In Selenium Webdriver there are three methods by using these methods we can validate.

Validating Methods:

All above methods will return Boolean. Either true or false if it returns ‘true’ we can say that element is clicked else not clicked.

Please check below code snippet for validation part:

Based on Boolean status and if condition we can validate easily. Please practice once on this automation practice page click here where you have radio button.

Please check entire program on how to handle radio button in selenium webdriver below,

Output:

Note: To run above program you need to download browser driver as I have downloaded chrome. You can download and work based on your desired web browser driver or you can click here to download from selenium website.


You May Also Like

About the Author: Azgar Khan

6 Comments

  1. Very use full information…. Can you please tell me how to select a radio element if all the attribute of that element are same like if value is also male for both radio button

    Thanks

    1. Thanks rawoof. if both elements having same attributes then you can create xpath with index. example:(//input[@value=’male’])[1] for male and (//input[@value=’male’])[2] for female.Hope you got the answer

Leave a Reply

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