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.
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.
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
.
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
In the third step, download the WebDriver manager Jar file from below link:
WebDriver Manager JarCopy 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.