tech beamers
  • Viral Tips 🔥
  • Free CoursesTop
  • TutorialsNew
    • Python Tutorial
    • Python Examples
    • C Programming
    • Java Programming
    • MySQL Tutorial
    • Selenium Tutorial
    • Selenium Python
    • Playwright Python
    • Software Testing
    • Agile Concepts
    • Linux Concepts
    • HowTo Guides
    • Android Topics
    • AngularJS Guides
    • Learn Automation
    • Technology Guides
    • Python
    • C
    • Java
    • MySQL
    • Linux
    • Web
    • Android
    • AngularJS
    • Playwright
    • Selenium
    • Agile
    • Testing
    • Automation
    • Best IDEs
    • How-To
    • Technology
    • Gaming
    • Branding
  • Interview & Quiz
    • SQL Interview
    • Testing Interview
    • Python Interview
    • Selenium Interview
    • C Sharp Interview
    • Java Interview
    • Web Development
    • PHP Interview
    • Python Quizzes
    • Java Quizzes
    • Selenium Quizzes
    • Testing Quizzes
    • HTML CSS Quiz
    • Shell Script Quizzes
    • Python Interview
    • SQL Query Interview
    • SQL Exercises
    • Selenium Interview
    • Playwright Interview
    • QA Interview
    • Manual Testing
    • Rest API Interview
    • Linux Interview
    • CSharp Interview
    • Python Function Quiz
    • Python String Quiz
    • Python OOP Quiz
    • Python DSA Quiz
    • ISTQB Quiz
    • Selenium Quiz
    • Java Spring Quiz
    • Java Collection Quiz
    • JavaScript Quiz
    • Shell Scripting Quiz
  • ToolsHot
    • Python Online Compiler
    • Python Code Checker
    • C Online Compiler
    • Review Best IDEs
    • Random Letter Gen
    • Random Num Gen
    • Online Python Compiler
    • Python Code Checker
    • Python Code Quality
    • Username Generator
    • Insta Password Generator
    • Google Password Generator
    • Free PDF Merger
    • QR Code Generator
    • Net Worth Calculator
tech beamers
Search
  • Viral Tips 🔥
  • Free CoursesTop
  • TutorialsNew
    • Python Tutorial
    • Python Examples
    • C Programming
    • Java Programming
    • MySQL Tutorial
    • Selenium Tutorial
    • Selenium Python
    • Playwright Python
    • Software Testing
    • Agile Concepts
    • Linux Concepts
    • HowTo Guides
    • Android Topics
    • AngularJS Guides
    • Learn Automation
    • Technology Guides
  • Interview & Quiz
    • SQL Interview
    • Testing Interview
    • Python Interview
    • Selenium Interview
    • C Sharp Interview
    • Java Interview
    • Web Development
    • PHP Interview
    • Python Quizzes
    • Java Quizzes
    • Selenium Quizzes
    • Testing Quizzes
    • HTML CSS Quiz
    • Shell Script Quizzes
  • ToolsHot
    • Python Online Compiler
    • Python Code Checker
    • C Online Compiler
    • Review Best IDEs
    • Random Letter Gen
    • Random Num Gen
Follow US
© TechBeamers. All Rights Reserved.
Selenium Tutorial

Selenium Exercise – Automate a Purchase from Flipkart (Tested & Verified)

Last updated: May 10, 2025 6:50 am
Meenakshi Agarwal
By
Meenakshi Agarwal
Meenakshi Agarwal Avatar
ByMeenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
Follow:
No Comments
3 months ago
Share
10 Min Read
SHARE

In this tutorial, you will learn how to automate adding a book to the cart on the Flipkart website using Selenium and Java. This updated exercise uses Selenium 4, and it’s designed to help you build hands-on experience for practical tasks. If you’re preparing for a Selenium interview, interviewers might ask you to write code that automates tasks on a website. This code example provides a real-world solution for adding a book to your cart on Flipkart.

Contents
  • Use Selenium 4 to Add a Book to the Cart on Flipkart
    • Steps to Add a Book to the Cart
    • Sample Code to Add a Book to the Cart
    • Build and Run the Code with Minimal Efforts
  • Final word – Selenium to Automate a Purchase from Flipkart

This is part of our ongoing series of Selenium WebDriver exercises, where we aim to teach you hands-on coding along with the core concepts. We believe that understanding the theory is important, but being able to write and debug code is even more essential. Since this is an advanced WebDriver topic, you should be familiar with how to form XPath or CSS selectors to locate elements on a webpage.

We’ve made the source code and XPaths flexible, so you can still use them even if Flipkart changes its website layout.

If you’re interested in learning more about XPath and how to use it effectively, be sure to check out the other posts linked below.

  • Learn to Use FirePath to Find an XPath
  • 8 Unique Ways to Use Locators in Selenium

Use Selenium 4 to Add a Book to the Cart on Flipkart

Here’s a simple guide and code to add a book to the cart on the Flipkart website using Selenium. This code will help you search for a book and add it to your cart automatically.

We’ll walk through each step clearly, so it’s easy to understand and follow.

Steps to Add a Book to the Cart

  • Launch Chrome Browser and Maximize Window: The code will open the Chrome browser and make sure it’s fully visible.
  • Navigate to Flipkart: The code will visit the Flipkart website.
  • Search for a Book: It will search for a book using a keyword (like “Selenium”). You can change this keyword to any book you want to search for.
  • Click on the Search Result: Once the book search results are loaded, the code will click on the first result to view more details.
  • Select a Book: It fetches the list of books displayed and clicks on the first book. You can change the XPath to select a different book if you like.

    Example XPath for selecting the first book: (//a[contains(.,'Selenium')])[1]
  • Open the Book Page: After selecting a book, it will open the book’s details page.
  • Click on the “Add to Cart” Button: The code will click the “Add to Cart” button. There might be multiple buttons on the page, so we select the first one using XPath.

    XPath to select the first “Add to Cart” button: (//button[contains(.,'Add to Cart')])[1]
  • Verify the Book in Cart: Finally, the script will check if the book has been added to the cart and confirm that the cart has the right book.

Also Read: 10 Selenium Coding Problems

Sample Code to Add a Book to the Cart

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

// FlipkartCart.java
//
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;

public class FlipkartCart {

  private static final String LOGIN_POPUP_CLOSE = "//button[contains(text(),'✕')]";
  private static final String SEARCH_FIELD = "input[title='Search for products, brands and more']";
  private static final String PRODUCT_CARD = "a[href*='/p/']";
  private static final int TIMEOUT_SECONDS = 15;

  private static WebDriver driver;
  private static WebDriverWait wait;

  public static void main(String[] args) {
    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
    wait = new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT_SECONDS));

    try {
      driver.manage().window().maximize();
      driver.get("https://www.flipkart.com");

      wait.until(webDriver -> ((JavascriptExecutor) webDriver)
        .executeScript("return document.readyState").equals("complete"));

      searchAndSelectProduct("Selenium Book");
      addToCart();
      takeScreenshot("before-close");
      Thread.sleep(3000); // Optional visual confirmation
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      driver.quit();
    }
  }

  private static void searchAndSelectProduct(String product) {
    try {
      wait.until(webDriver -> ((JavascriptExecutor) webDriver)
        .executeScript("return document.readyState").equals("complete"));

      WebElement searchBox = wait.until(ExpectedConditions.elementToBeClickable(
        By.cssSelector("input[title*='Search']")));
      searchBox.sendKeys(product + Keys.ENTER);

      wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(PRODUCT_CARD)));

      WebElement firstProduct = driver.findElements(By.cssSelector(PRODUCT_CARD)).get(0);
      String originalWindow = driver.getWindowHandle();
      Set < String > oldWindows = driver.getWindowHandles();

      ((JavascriptExecutor) driver).executeScript("arguments[0].click();", firstProduct);

      boolean newWindowOpened = wait.until(d -> d.getWindowHandles().size() > oldWindows.size());
      if (!newWindowOpened) {
        takeScreenshot("no-new-tab");
        throw new RuntimeException("New tab/window did not open after clicking product.");
      }

      for (String handle: driver.getWindowHandles()) {
        if (!handle.equals(originalWindow)) {
          driver.switchTo().window(handle);
          break;
        }
      }

    } catch (Exception e) {
      takeScreenshot("error-search");
      throw new RuntimeException("Failed during search/select: " + e.getMessage());
    }
  }

  private static void addToCart() {
    try {
      WebElement addBtn = wait.until(ExpectedConditions.presenceOfElementLocated(
        By.xpath("//button[contains(., 'Add to cart') or contains(., 'ADD TO CART')]")));
      ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", addBtn);
      wait.until(ExpectedConditions.elementToBeClickable(addBtn)).click();

      wait.until(ExpectedConditions.or(
        ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'Added')]")),
        ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'Place Order')]"))
      ));

      System.out.println("Product added to cart successfully.");
    } catch (Exception e) {
      takeScreenshot("error-add-to-cart");
      throw new RuntimeException("Failed to add to cart: " + e.getMessage());
    }
  }

  private static void takeScreenshot(String prefix) {
    try {
      File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
      String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"));
      File dest = new File(prefix + "-" + timestamp + ".png");
      Files.copy(screenshot.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
      System.out.println("Screenshot saved: " + dest.getAbsolutePath());
    } catch (IOException e) {
      System.err.println("Failed to capture screenshot: " + e.getMessage());
    }
  }
}

If you like to practice more, here are 10 Java coding questions for testers. You are most likely going to enjoy solving these exercises.

Build and Run the Code with Minimal Efforts

We tested the set up, code build, and execution on a Windows 11 laptop. Our goal was to keep the set up and steps to the minimal. We wanted to avoid any installation just for the sake of testing this this solution. You can also follow this approach and it will even help you set up a nightly test automation job with minimal footprint.

Firstly, download the portable Java SDK (JDK) from below link. It is zip file, extract the content and copy in a folder named as jdk.

Portable JDK

Secondly, download the latest Selenium 4 Jar file. You’ll only get its zip package, so extract the file like this from the bundle: selenium-java-4.32.0.jar

Selenium 4 Jar

In the third step, download the WebDriver manager Jar file from below link:

WebDriver Manager Jar

Copy both the above Jars into a folder named libs or create it as needed.

The final step is to create a run.bat file to build and run our FlipkartCart.java code.

@echo off
setlocal
set JAVA_HOME=%~dp0jdk
set PATH=%JAVA_HOME%\bin;%PATH%

javac -cp "libs\selenium-java-4.32.0.jar;libs\webdrivermanager-6.1.0-fat.jar" FlipkartCart.java
java -Dwdm.logLevel=DEBUG -cp "libs\*;." FlipkartCart

echo .
pause

Once saved, you just need to double click and run/test the above Selenium exercise. We exactly followed the same steps to verify the whole thing. Just, in case, you find different versions for any of the Java, Selenium, or WebDriver manager, then place them correctly in run.bat. If you face even a single issue, let us know via comments. We’ll solve your problem certainly.

The final directory structure must look like the below:

FlipkartDemo/
├── jdk/          # Portable JDK 17
├── libs/
│   ├── selenium-java-4.32.0.jar
│   └── webdrivermanager-6.1.0-fat.jar
├── run.bat
└── FlipkartCart.java

Final word – Selenium to Automate a Purchase from Flipkart

It is our attempt to give you the correct 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 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.

Lastly, if you fail to download or get any of the required components, please use the comment box to connect with us. We will fix and update the broken links.

Related

TAGGED:Webdriver Exercises
Share This Article
Whatsapp Whatsapp LinkedIn Reddit Copy Link
Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

List of Topics

Stay Connected

FacebookLike
XFollow
YoutubeSubscribe
LinkedInFollow

Subscribe to Blog via Email

Enter your email address to subscribe to latest knowledge sharing updates.

Join 991 other subscribers

Continue Reading

  • A 10 Min Guide: Download and Set up Selenium GridJul 6
  • Webdriver Wait Commands and ExamplesJul 7
  • Selenium Grid Webdriver Code ExampleJul 11
  • Understand Webdriver Fluent Wait with ExamplesJul 15
  • Mastering Assertions in Selenium Using TestNGJul 17
  • Implement Page Object Model in SeleniumAug 17
  • Selenium Java App to Find Blog Rank in GoogleOct 12
  • Best Selenium Practice Websites in 2025Feb 8
  • Six Steps To Setup Selenium WebDriver Project in EclipseMar 1
  • Selenium IDE Download And Installation GuideMar 12
View all →

RELATED TUTORIALS

How to Use Internet Explorer Driver to Run Webdriver Tests

How to Use Internet Explorer Driver with Selenium

By Meenakshi Agarwal
1 year ago
Selenium Webdriver Download and Install

Selenium Webdriver – Download and Install Stable Versions

By Meenakshi Agarwal
1 year ago
Selenium Webdriver Commands Essential for Test Automation

Learn Basic Selenium Webdriver Commands

By Harsh S.
7 months ago
Selenium Webdriver Skills for Test Automation Developers

Essential Selenium Webdriver Skills for Test Automation

By Meenakshi Agarwal
12 months ago
© TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use