Handle datePicker in selenium using JavaScript

In this article, will talk about how to Handle datePicker in selenium using JavaScript.
Suggested post to read:
In old applications, the datepicker was in old style, that is, it was a kind of dropdowns, by using select class. But in new applications now, Datepicker are not Select element.
Datepicker are in fact table with set of rows and columns. To select a date, you just have to navigate to the cell where our desired date is present. Look at the below snapshot.
So, to handle this datePicker, we will write a java script, in which firstly we will enable the datebox (which is restricted by default to enter the value manually rather than selecting it from calendar pop-up). Then We will clear that filed & then enter the date by using sendKeys() method.
Look at the below example –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HandleDatePcikerUsingJavaScript {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("https://www.redbus.in/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //This will select From date 
  WebElement elementFromDate = driver.findElement(By.id("onward_cal"));
  ((JavascriptExecutor)driver).executeScript ("document.getElementById('onward_cal').removeAttribute('readonly',0);"); // Enables the from date box
  elementFromDate.clear();
  elementFromDate.sendKeys("18-Aug-2017"); //Enter date in required format
  
  
 }

}

Hope this helps !!

How to use JavaScriptExecutor in selenium WebDriver?

In this article i will talk about how to use JavaScriptExecutor in Selenium WebDriver.

Suggested post to read:

 What is JavaScriptExecutor in selenium WebDriver?

Let us understand first what is JavaScriptExecutr. It is an interface which is used to execute JavaScript in selenium Webdriver code.

Selenium WebDriver uses pre-defined locators like id, class, Xpath, name, link etc. to locate the elements on webpage. So, in some cases, it becomes difficult to locate element or sometimes you may face consistency problem in locating element due to webpage code.

Many Situations occur in your project where code written with selenium – java (any language binding) does not work (at all or effectively).

There would be few tricky scenarios where just Webdriver object is not sufficient enough or optimum enough to handle with java for e.g. in few of my applications, the web page rendered is very long, and while doing operations with elements, I got errors. So, I used JavaScript in my script to handle the case. Some other cases where JavaScript comes handy is handling pop ups and alerts.

In another case, dropdown wasn’t working for me (it was not properly coded by using select class). It was selecting the elements with are currently visible, wasn’t searching in to the whole list. So, in this case, I need to keep scrolling down continuously & at the same time keep checking If the required option is available to select & is getting selected.

So, there are certain advantages involved when we use the two (java, JavaScript) judiciously in automation scripts. Both the languages are great in their own space.

What are the advantages of JavaScriptExecutr in Selenium?

1.      JavaScript is very efficient & accurate, as compare to the scripts written with Selenium-Java
2.     JavaScript executor allows you to run pure JavaScript code irrespective of the Selenium language binding (Java, C#, Python etc.) you are using.
3.     By using JavaScript, you can directly interact and /or alter elements on the page, more or less, like the page developer has done.
4.     JavaScript being a language which works very well with HTML offers innumerous workarounds/hacks on the page.
5.     JavaScript is recommended to use when Selenium – Java code tends to break for certain scenario, where JavaScript works perfectly.
6.     JavaScript is quite easy to pick up with the least amount of setup required. No special setup is required while using it with selenium
How to use JavaScriptExecutr (JavaScriptExecutr Syntax) –
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
Where –
script – The JavaScript to execute
Arguments – The arguments to the script. (Optional)
Let us see few of the uses where we can use javaScripts in selenium WebDriver code.
       1.       To refresh browser
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
       2.       To get Webpage title
JavascriptExecutor js = (JavascriptExecutor)driver;
String sText =  js.executeScript(“return document.title;”).toString();
        3.       To click on the button
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
      where, element is the button webElement where you wanted to click.
         4.       To Scroll down the webpage
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.scrollBy(0,50)");
-> This is to scroll 50 pixels down.
If you want to scroll down till the end of webpage, then –
  js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
        5.       To navigate to webpage –
JavascriptExecutr js = (JavascriptExecutr)driver;
js.executeScript("window.location = ‘URL-TO-BE-NAVIGATED’");

          6.       To enter text in textbox using JavaScript
           JavascriptExecutr js = (JavascriptExecutr)driver; 
           js.executeScript(“document.getElementById(‘lst-ib’).value = ‘Text to be searched’;”);
Example of JavaScriptExecutor –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class JavaScriptExample {

 public static void main(String[] args) {
  
  WebDriver driver = new FirefoxDriver();

  //Navigate to google.com using javascript
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.location = 'https://www.google.co.in'");
 
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //Enter the text in textbox using javascript
  js.executeScript("document.getElementById('lst-ib').value = 'Text to be searched';");
  
  //Click on the button using javascript
  WebElement element  = driver.findElement(By.xpath("//*[@id='tsf']/div[2]/div[3]/center/input[1]"));
  js.executeScript("arguments[0].click();", element);

  //Get page Title using JavaScript
  String PageTitle =  js.executeScript("return document.title;").toString();
  System.out.println("Page title is: "+PageTitle);
  
  //To Refresh the browser using JavaScript
  js.executeScript("history.go(0)");
  
  //To Scroll Down the webpage 
    js.executeScript("window.scrollBy(0,50)");
    
    //to Scroll the webpage to bottom of page
    js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
 }

}

Hope this example helps little bit to understand how to use JavaScript in selenium – java code.

How to check if element / object is present on webpage?

In this article we will talk about, to check if particular element present on webpage or not.

In some cases, it is required to verify if element exist, click on the element if it exist.
Let us see how this can be achieved.
             1.       First Navigate to website.
             2.       We will use findElements here, so that we can check for all element with particular locator is present on webpage.
            3.       Get all the elements in a list.
            4.       If list is not empty, this means, element exist
            5.       If list is empty, this means, element is not present on webpage.
Look at the below example.
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CheckIfElementPreesntOnWebPage {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://demowebshop.tricentis.com/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();

  if (driver.findElements(By.xpath("//a[@class='ico-login1']")).size() != 0 )
    {
   System.out.println("Element is present on WebPage");
  }
  else {
   System.out.println("Element is not present on webpage");
  }
 }

}

Refer below video –

Hope above example helps !!!

Writing Excel files using Apache POI

Let us talk about writing excel files using apache POI. In earlier post, we saw that how can we read the data (get the data ) from excel file.  Refer below posts for this.

1. How to read an excel 2003 (.xls) file using Apache POI

2. How to read an Excel 2007 (.xlsx) file using Apache POI

In this post, we will talk about, how can we write / update data in excel sheet.
For Writing the data, we need FileOutputStream.
We need to find out the cell which we are going to write in to. Then use setCellValue method to write the value to the desired cell.
Steps to update excel file will be:
  •     Open excel file in input mode (inputstream)
  •     Use POI API and read the excel content
  •     Update cell’s value using different setCellValue methods.
  •     Close the excel input file (inputstream)
  •     Open same excel file in output mode (outputstream)
  •     Write content of updated workbook in output file
  •     Close output excel file
Below example illustrate the same.
package apachePOI;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteExcelFileClass {

 @SuppressWarnings("resource")
 public static void main(String[] args) throws IOException {
  
  try {
   FileInputStream file = new FileInputStream(new File("C:UsersPrakashDesktopTestData - Only String.xlsx"));

   XSSFWorkbook workbook = new XSSFWorkbook(file);
   XSSFSheet sheet = workbook.getSheetAt(0);
   Cell cell = null;

   //Update the value of cell
   cell = sheet.getRow(1).getCell(2);
   cell.setCellValue(cell.getNumericCellValue() * 2);
   cell = sheet.getRow(2).getCell(2);
   cell.setCellValue(cell.getNumericCellValue() * 2);
   cell = sheet.getRow(3).getCell(2);
   cell.setCellValue(cell.getNumericCellValue() * 2);
   
   file.close();
   
   FileOutputStream outFile =new FileOutputStream(new File("C:UsersPrakashDesktopTestData - Only String.xlsx"));
   workbook.write(outFile);
   outFile.close();
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 
 }

}

Hope this helps !!!!

How to read excel 2003 (.xls) file using Apache POI?

Before you start with how to read excel 2003 file using apache poi, suggested pre-requisites to read –

Introduction to Apache POI

How to set up Apache POI in java – selenium project.

To start with the article, about how to read an excel file using Apache POI, Pre-rwquisite is, you have configured Apache POI in your project. If not, refer above link.
As we saw earlier, HSSF is the POI Project’s pure Java implementation of the Excel ’97(-2007) file format. Whereas XSSF is the POI Project’s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
Let us understand about excel first.
First find out the excel file, known as Workbook here. Then within a workbook, we have multiple sheets. Go to the desired sheet using sheet name / sheet index. Then go to row & column position & get the cell data.
Below are the steps to Read excel sheet

     1.     Create object of the File, provide file path where your excel sheet is placed. Make sure that Excel file is in 2003 format (.xls format).

           2.       Get the file in FileInputStream which we will use for reading excel sheet.
           3.       Now use HSSFWorkbook class to get the desired workbook from FileInputStream.
              HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
 
          4.       Get the required sheet using class HSSFSheet (of the above workbook).
               HSSFSheet sheet=wb.getSheetAt(0);
         5.       Now get the data from sheet using object created by HSSFSheet.
Look at the below example.
There are two ways
            1.       If the excel sheet has only String data (or one type of data)
            2.       If the excel sheet has combination of data like String /int/Boolean etc.
Consider the First point when Excel sheet has only one type of data. Below ScreenShot shows the input excel file.
Observe the below piece of code, which will be used to read excel file data (have only one type of data – String here)
package apachePOI;

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class Read2003FormatExcel {

 public static void main(String[] args) throws Exception {

  //location of your file - filepath
  String filepath = "C:UsersPrakashDesktopTestData.xls";
  
  //Create File object with above file path
  File srcFile = new File(filepath);
  
  //Create FileInputStream for above srcFile - to read file
  FileInputStream fis = new FileInputStream(srcFile);
  
  //Excel file is nothing but workbook, so create workbook object.
  HSSFWorkbook wb = new HSSFWorkbook(fis);
  
  //Go to the desired sheet, here index 0 means first tab
  HSSFSheet sheet = wb.getSheetAt(0);
  
  //get total number of rows & columns so that we can iterate over it.
  int TotalNumOfRows = sheet.getLastRowNum()+1;
  int TotalNumOfCols = sheet.getRow(0).getLastCellNum();
  
  //Iterate over the sheet, using total number of rows and columns
  for (int i = 0; i < TotalNumOfRows; i++ ){
   for (int j = 0; j < TotalNumOfCols; j++){
    
    //get the cell data using row number and column number of the cell.
    HSSFRichTextString cellData = sheet.getRow(i).getCell(j).getRichStringCellValue();   
    System.out.println(cellData);
   }
  }
  
 }

}
Now, in Another case, when Excel sheet contain all type of data, example – String / int / Boolean etc.

Observe below piece of code – to read data from excel sheet containing all type of data (can be used even if excel sheet has one type of data)
package apachePOI;

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class Read2003FormatExcelUsingIterator {

 public static void main(String[] args) throws Exception {

  //location of your file - filepath
  String filepath = "C:UsersPrakashDesktopTestData.xls";
  
  //Create File object with above file path
  File srcFile = new File(filepath);
  
  //Create FileInputStream for above srcFile - to read file
  FileInputStream fis = new FileInputStream(srcFile);
  
  //Excel file is nothing but workbook, so create workbook object.
  HSSFWorkbook wb = new HSSFWorkbook(fis);
  
  //Go to the desired sheet, here index 0 means first tab
  HSSFSheet sheet = wb.getSheetAt(0);
  
  //get total number of rows & columns so that we can iterate over it.
  int TotalNumOfRows = sheet.getLastRowNum()+1;
  int TotalNumOfCols = sheet.getRow(0).getLastCellNum();
  
  Iterator<Row> itr = sheet.rowIterator();
  while (itr.hasNext()){
   Row row = itr.next();
   
   Iterator<Cell> itrCell = row.cellIterator();
   
   while (itrCell.hasNext()){
    Cell cell =  itrCell.next();
    switch (cell.getCellType()){
    case Cell.CELL_TYPE_NUMERIC:
     System.out.println("cell type is Numeric: "+cell.getNumericCellValue());
     break;
    case Cell.CELL_TYPE_STRING:
     System.out.println("cell type is String: "+cell.getStringCellValue());
     break;
    
    }
   }
  }
  
 }

}
Hope This Helps !!!! do post your questions if any !!!

Suggested next article to read –     Writing Excel files using Apache POI

How to setup Apache POI in java – selenium Project.

In this article i will talk about how to setup apache POI in Selenium java project under eclipse.

Suggested post to read –  Apache POI Introduction

Setting up Apache POI in a java – selenium project is very easy. Again as like selenium, Apache POI is a suite of jar files. So, setting up Apache POI means adding these jar files to a project. Let us see how this can be achieved.
Step1: Download Apache POI.  
   You can download Apache POI from its official website (https://poi.apache.org/download.html). Latest version of Apache POI is 3.16 (a stable release) as of today.
To Download Apache POI – Click here. Version 3.16
Step2: Extract the downloaded POI jar files.
Once zip file is downloaded from above link, extract the jar files to some location.
Step 3: Create new Java project.
To know about how to create new project, refer step 2 of below post.

How to create java project in eclipse IDE

Step4: Add extracted jar files in to java – selenium project.
Follow below steps to know how can we add the jar files in to a project.
First, right click on project created in step 3 here.
Then Go to “Build path” -> “Configure Build Path”
 Then Click on “Add External Jar” option.
Then select all extracted jar files and click on apply and save.
That’s it, you have configured Apache POI in your java – selenium project. You can start using excel files in java -selenium project.
Follow next articles to know how to used Excel files in java – selenium project.
Refer –

How to read an excel 2003 (.xls) file using Apache POI

How to read an Excel 2007 (.xlsx) file using Apache POI

Writing Excel files using Apache POI

Apache POI Introduction

What is Apache POI?

Apache POI is the java API for Microsoft documents like excel, word, PowerPoint, outlook, Visio, Publisher etc.
Some time, while automating web application, it is expected to read the input data from excel file, Sometime it is expected to generate reports in excel / word etc. So, in order to deal with this, one needs Apache POI. – which is a java API for Microsoft documents.
It is used to create new Microsoft document (like excel / word etc), to modify them, to access data from excel file / word file by using java programs.

POI have various components for various Microsoft documents. Below are the components of POI.
Components of Apache POI. – 
Excel (SS=HSSF+XSSF+SXSSF) –
HSSF is the POI Project’s pure Java implementation of the Excel ’97(-2007) file format. XSSF is the POI Project’s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
PowerPoint (SL=HSLF+XSLF) –
HSLF is the POI Project’s pure Java implementation of the Powerpoint ’97(-2007) file format.
Word (WP=HWPF+XWPF) –
HWPF is the name of our port of the Microsoft Word 97(-2007) file format to pure Java. It also provides limited read only support for the older Word 6 and Word 95 file formats.
The partner to HWPF for the new Word 2007 .docx format is XWPF. Whilst HWPF and XWPF provide similar features, there is not a common interface across the two of them at this time.
Outlook (HSMF) –
HSMF is the POI Project’s pure Java implementation of the Outlook MSG format.
Visio (HDGF+XDGF) –
HDGF is the POI Project’s pure Java implementation of the Visio binary (VSD) file format. XDGF is the POI Project’s pure Java implementation of the Visio XML (VSDX) file format.
Publisher (HPBF) –
HPBF is the POI Project’s pure Java implementation of the Publisher file format.
Official WebSite of Apache POI is: https://poi.apache.org/
It is very common to use Excel file for Automation purpose. Here is how to get started with using excel file for automation purpose / data driven testing.
1. Download the latest release of the library here: Apache POI – Download Release Artifacts
2. Extract the zip file and add the appropriate JAR files to your project’s classpath:
– If you are reading and writing only Excel 2003 format, only the file poi-VERSION.jar is enough.
– If you are reading and writing Excel 2007 format, you have to include the following files:
  • poi-ooxml-VERSION.jar
  • poi-ooxml-schemas-VERSION.jar
  • xmlbeans-VERSION.jar
For Automation testing using Selenium WebDriver, we do not need all these things. What we need mostly is, how to read / write excel sheet (2003 / 2007 format). We may not be concerned about other uses of Apache POI.
So, let us study apache POI with below articles.

      1.       How to setup Apache POI in java – selenium Project.

           2.       How to read an excel 2003 (.xls) file using Apache POI

           3.       How to read an Excel 2007 (.xlsx) file using Apache POI

           4.       Writing Excel files using Apache POI

Hope this helps !!!!

First test using TestNG Framework.

First TestNG Test – How to run selenium test using TestNG framework? We have seen basic details about TestNG framework, how useful it is.

Suggested post to Read:      Introduction to TestNG

Now, let us see, how can we run the selenium WebDriver test using TestNG framework.

The basic pre-requisite for this is, to have testing jar file.
To know about how to install TestNG, refer below post.

Suggested post to Read: How to install TestNG in Eclipse IDE

Let us consider very basic test to launch gmail.com & get the title of the page.
Note that, when we use TestNG framework, there is no need to write main method on our test. We can run the test cases without main method.
In order to write a test case in TestNG framework, it is very simple. Just create some method for your test. Write test code in that method.
Now, here is role of TestNG framework. We can use @Test annotation for running the code from that method without writing main method.
Make sure that, you configure testing.jar in your project.
After this, when you are asked to import “Test” annotation, make sure that, you import it from testing. Refer below screen shot.
here is the sample code for this –
package basicsOfSelenium;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class FirstSeleniumTest {
 @Test
 public  void gmailTest() {
   WebDriver driver = new FirefoxDriver();
   driver.navigate().to("https://www.google.co.in");
   String TitleOfPage = driver.getTitle();
   System.out.println("Title of Current page is : "+TitleOfPage);
     driver.close();
 }
}
In above code, @Test annotation is used to run the method – gmailTest().
You can right click on the program, Run As -> TestNG Test
After the run is successful,  You can see the report as in below image –
Note that, when you run TestNG test, the XML file will be generated in a temp folder & system will use that testing.xml file to run our test.
To know more about TestNG.xml –

Refer post: what is TestNG.xml 

Hope this helps !!!!

How to handle multiple Check Boxes in Selenium WebDriver?

A group of check boxes is created by giving two or more checkboxes the same control name. In the above example, the checkbox group control name is “color”. However, each checkbox in the group has a different associated value specified by the value attribute.

When a user selects (checks) a checkbox, its value gets assigned as the current value of the checkbox group’s control name. A checkbox group’s control name may conceivably get paired with several current values if the user selects more than one checkbox.
Let us consider below screen which show the example of check boxes.
 
Source code for check boxes shown in above image is:
My favourite colors are:<br><br>
<input type="checkbox" name="color" value="red">
Red<br>
<input type="checkbox" name="color" value="yellow">
Yellow<br>
<input type="checkbox" name="color" value="blue">
Blue<br>
<input type="checkbox" name="color" value="orange">
Orange<br>
<input type="checkbox" name="color" value="green">
Green<br>
<input type="checkbox" name="color" value="purple"> 
Purple<br>

By observing above HTML code, we can see that, name of all the check boxes is same. So what we can do is, get the list of all check boxes by using attribute name and iterate over it. If found matching, then click on it.

Below piece of code illustrate the same. –

package learnAboutActionsClass;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CheckBoxInSelenium {

 public static void main(String[] args) {

  
  WebDriver driver = new FirefoxDriver();
  
  driver.navigate().to("http://www.ironspider.ca/forms/checkradio.htm");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  List<WebElement> ListOfCheckBoxes = driver.findElements(By.name("color"));
  System.out.println("Number of check boxes pesent are: "+ListOfCheckBoxes.size());
  
  for(int i=0; i< ListOfCheckBoxes.size() ; i++) {
   if(ListOfCheckBoxes.get(i).getAttribute("value").equalsIgnoreCase("Red")){
    ListOfCheckBoxes.get(i).click();
   }
       }
  
 }

}

Refer below video for same explanation –

 

Refer below post for complete example of Automation of Registration page using Selenium WebDriver.
Hope this Helps!!!

How to Handle Radio Button in Selenium WebDriver?

I think radio button I’d is dynamically generated. Try using By.name() with WebDriverWait to wait until radio button visible.

Performing radio button select operation is quite easy if you want to select the radio button without checking if any of the button is selected by default.

In most of the cases, ID attribute of the radio button will serve purpose, since ID attribute will be different for each radio button. Note that, most of the time, name will be same for all radio buttons of specific field. So, if you wanted to use list & check if any of the button is selected, you can use name attribute.

Let us consider below example. –

As shown on above screen shot, there are 2 radio buttons, let us see, how can we select them.
Below is the HTML code for these radio buttons.

<div class="radio-inline">
<label class="top" for="id_gender1">
<div id="uniform-id_gender1" class="radio">
<span>
<input id="id_gender1" type="radio" value="1" name="id_gender">
</span>
</div>
Mr. 
</label>
</div>
<div class="radio-inline">
<label class="top" for="id_gender2">
</div>
</div>
So, as you can see, ID attribute for each radio button is different, we can use it for selection. Lets see how to do this.

                String gender = "female";
  WebElement RadioButtonMr = driver.findElement(By.xpath("//*[@id='id_gender1']"));
  WebElement RadioButtonMrs = driver.findElement(By.xpath("//*[@id='id_gender2']"));
  
  if (gender.equalsIgnoreCase("male")){
   RadioButtonMr.click();
  }
  if (gender.equalsIgnoreCase("Female")){
   RadioButtonMrs.click();
  }

Above code is a very simple approach how can we select radio button.

Another way to select the radio buttons is by using the value attribute.

 Let us see, how this can be achieved.

As we saw earlier, name attribute will be same for radio buttons. So, what we can do is, get the list of radio buttons by unique name and iterate on it.
String valueOfGender = "2"; //in this case, value is integer, it can be String in most of the cases. 
List<WebElement> RadioButtonList = driver.findElements(By.name("id_gender"));
  System.out.println("Total numer of Radio Buttons for gender field is: " +RadioButtonList.size());
  
  for (int i = 0; i < RadioButtonList.size(); i++){
   String gend = RadioButtonList.get(i).getAttribute("value");
   if (gend.equalsIgnoreCase((valueOfGender))){
    RadioButtonList.get(i).click();
    break;
   }
   
  }

Refer below post for complete example of Automation of Registration page using Selenium WebDriver.

Refer below video –

Hope this helps !!!