Friday 16 June 2017

Selenium WebDriver : Working with Radio Buttons

In this post, we are going to see how one can interact with Radio buttons present on a Web Page and select one of them. Radio Buttons are nothing but a list of options in which user is allowed to select exactly ONE option.

We are going to see how it can be done using Selenium WebDriver. Very simple, just stick to this post till the end. Also we have our YouTube Channel that will cover all the topics we are covering in this blog. So don't forget to subscribe to the channel for more interesting Test Automation videos. 

YouTube Channel : Click Here

So these are the HTML Radio Buttons as shown in below image :




HTML code looks like this :


  <input type="radio" name="animal" value="Bird"> Bird<br>
  <input type="radio" name="animal" value="Cat"> Cat<br>
  <input type="radio" name="animal" value="Dog"> Dog<br>
  <input type="radio" name="animal" value="Rabbit"> Rabbit<br>
  <input type="radio" name="animal" value="Pig"> Pig<br>




Now in order to select one of the Radio Button options, we just need to locate the appropriate option (Web Page Element) and click on that option using the click() method we already discussed in previous posts.



So in order to select Bird in above example, check the following code snippet : (Assuming the Web Page contains above HTML code)



public class Sample {
public static void main(String[] args) {
//Initialize Browser
System.setProperty("webdriver.gecko.driver", "Path to geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("Web Page URL");

//Find Element and Click
WebElement element = driver.findElement(By.cssSelector("input[value='Bird']"));
element.click();
}
}



driver.findElement(By.cssSelector("input[value='Bird']")); is used to locate the Radio Button option containing the value Bird.



CssSelector is used to find the required Web Page element (option) and click on that option. "tag[attribute='value']" is used as the CssSelector in the absence of ID or ClassName. 
The above code snippet will select the Bird option by using the click() method provided by Selenium WebDriver.


That's it in this post. Hope you are following the sequence of posts in this blog for better understanding of Test Automation using Selenium.
Don't forget to subscribe to our YouTube Channel for better understanding via videos and more examples.

Happy Learning.

YouTube Channel : Click Here

No comments:

Post a Comment