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:
package mypack; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Class1 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); } }
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:
Mango
Mango
Mango
Ladyfinger
Potato
Tomato
The code for navigating to the above html file is given below:
package mypack; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Class1 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("file:///C:/Users/admin/Desktop/radio.html"); } }
The output of the above code:
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:
The code shown below handles the radio button by using the customized path.
package mypack; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Class1 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("file:///C:/Users/admin/Desktop/radio.html"); driver.findElement(By.xpath("//input[@value='Banana']")).click(); } }
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
Source code
package mypack; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Class1 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("file:///C:/Users/admin/Desktop/radio.html"); int a = driver.findElements(By.xpath("//input [@name='group1']")).size(); System.out.println(a); for(int i=1;i<=a;i++) { driver.findElements(By.xpath("//input[@name='group1']")).get(2).click(); } }}
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