Home » Selenium WebDriver Handling Radio Buttons

Selenium WebDriver Handling Radio Buttons

by Online Tutorials Library

Handling Radio buttons

In this section, you will learn how to handle radio buttons in selenium web driver.

Following are the steps to handle the radio buttons:

Step 1: Invoke the Google Chrome browser.

The code to invoke a Google chrome browser is given below:

Step 2: The second step is to navigate to the website in which we need to handle the radio buttons.

I created the html file which contains the radio buttons. The code is given below:

The code for navigating to the above html file is given below:

The output of the above code:

Handling Radio buttons

Step 3: Select the option Banana. We will locate the Banana radio button by inspecting its HTML codes.

There are two ways of handling the radio buttons:

  • By using the customized path:

The code shown below handles the radio button by using the customized path.

In the above, we use custom Xpath. Radio buttons contain a unique attribute, i.e., value, so we use the value attribute to handle the radio button.

Output

Handling Radio buttons

  • By handling the radio buttons dynamically.
    • We will first calculate the number of radio buttons. The following is the line of code which calculates the number of radio buttons.

      int a = driver.findElements(By.xpath(“//input [@name=’group1′]”)).size();

      The above line of code calculates the number of radio buttons whose name is group1.

    • Now, we will handle the radio buttons by using the index of a particular radio button.

      driver.findElements(By.xpath(“//input[@name=’group1′]”)).get(2).click();

Source code

In the above code, we use ‘for’ loop. Inside the ‘for’ loop, we find the third radio button of group1 by using the get(2) method.

Output

Handling Radio buttons

You may also like