Selenium Webdriver Exercise – Automate a Purchase from Flipkart

If you are planning for a Selenium Webdriver interview, then better be ready for the questions like how to add a book to the cart in Flipkart. It’s likely that the interviewer may ask you to write code for checking your hands-on knowledge. Hence, we choose to give you a fully functional code that requests for the purchase of a book from the Flipkart website.

This post is our second submission to the coding series of Selenium Webdriver exercises. We took this initiative because a right candidate needs to be good at concepts but must have a deep code level understanding as well. Since it’s an advance Webdriver topic, we expect that you know how to form an XPath/CSS or use it to access any web elements.

We tried our best to keep the source code and XPaths as relative as we could. So that you can even use it if there are changes on the Flipkart website. If you wish to read more about XPath and related concepts, then please have a look at the below post.

Selenium Webdriver Exercise – Add a book to the cart in Flipkart.

So, here is the complete code that adds a book to the cart in Flipkart website. In this sample code, we’ve used <FluentWait> to locate elements on the web page. Also, you’ll see the advanced usage of XPath locators that we used to identify the anchor texts and input elements like buttons. We make sure that the code should work without any code changes. However, if you see any issue, it could most likely be an XPath related issue. So, use <FirePath> in Firefox or <XPath Helper> in Chrome to finalize the right XPath of your web element.

Below is a summary of the steps that the sample code would run to add a book to the cart in Flipkart website.

1- Required Steps to Add a book to cart.

1- It would launch the Chrome browser and maximize the window.

2- Navigate to the Flipkart website and perform Login operation.

Note: You can change the username and password values or leave them as is. Since it’s just a demo, so you don’t need the credentials.

3- Now, it’ll search for the book keyword which we choose as <Selenium>. Change it if you want to.

4- In this step, the code will click to view the search results.

5- We’ll now fetch the list of books displayed and select the last one using the XPath locator given below. You change the XPath to choose a different book.

/* Select the last book from the search results. */

/* Select the first book from the search results. */

6- Click on the book link to open the next page.

7- It’s time to click the <Add to Cart> button, but there are five of them displayed on the page. So, we used the below XPath to locate the first link to perform the add cart action.

/* This is how we selected the first "Add to Cart" element on the page. */

(//input[contains(@value,'Add to Cart')])[1]

8- In the next few steps, we’ll view the cart, verify if the book entry and press continue to the fill the email.


2- Sample code to add a book to the cart.

Find out the working code that has the ability to add a book to the cart in Flipkart portal.

package com.techbeamers.exercises;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;


public class automateFlipkart {

	public static WebDriver driver;
	public static String driverPath = "C:\\workspace\\tools\\selenium\\";
	public static String sBookKey = "Selenium";
	private static final String sSearchBox = "fk-top-search-box";
	private static final String sSearchResult = "//li[contains(text(),'in')]//span";
	private static final String sBookName = "(//a[contains(.,'" + sBookKey + "')])[last()]";
	private static final String sAddToCart = "(//input[contains(@value,'Add to Cart')])[1]";
	private static final String sViewCartXPath = "(//a[contains(.,'view cart')])[1]";

	public static void initWebDriver(String URL) throws InterruptedException {

		// Setting up Chrome driver path.
		System.setProperty("", driverPath + "chromedriver.exe");
		// Launching Chrome browser.
		driver = new ChromeDriver();

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




		WebElement searchResult = getElement(By.xpath(sSearchResult));;

		WebDriverWait wait = new WebDriverWait(driver, 30);



		getElement(By.cssSelector("form[id='view-cart-form'] button")).click();
		getElement(By.xpath("//input[@id='email' and @name='email']")).sendKeys("");

		// pause for a second and close the browser.

	public static WebElement getElement(final By locator) {
		FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS)
				.pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

		WebElement element = wait.until(new Function<WebDriver, WebElement>() {

			public WebElement apply(WebDriver arg0) {
				return arg0.findElement(locator);


		return element;

	public static void flipkartLogin() {
		driver.findElement(By.linkText("Log In")).click();

		// TBD: Fill your username/password of flipkart.
		getElement(By.cssSelector("input[placeholder='Enter email/mobile']")).sendKeys("");
		getElement(By.cssSelector("input[placeholder='Enter password']")).sendKeys("");
		getElement(By.cssSelector("input[value='Login'][class='submit-btn login-btn btn']")).click();

		try {
		} catch (InterruptedException e) {
			// TBD: Auto-generated catch block.

	public static void endSession() {


Final word.

It is our attempt to give you the rightmost information so that you can keep yourself updated and acquainted. Hence, we always bring new topics on the plate to serve you what you need to get through to an interview.

If somehow this post manages to strike you, then please care to share it with your friends and other social media channels you like. And stay tuned for the next key topic that we’ll cover in the upcoming blog post.





  1. Rocky Jamello Reply
    • Meenakshi Agarwal Reply