TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Selenium Exercise – Automate a Purchase from Flipkart
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Selenium Tutorial

Selenium Exercise – Automate a Purchase from Flipkart

Last updated: Feb 29, 2024 9:46 am
By Meenakshi Agarwal
Share
7 Min Read
Selenium Webdriver - Add a book to the cart in Flipkart
Selenium Webdriver - Add a book to the cart in Flipkart
SHARE

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 on Flipkart. It’s likely that the interviewer may ask you to write code to check your hands-on knowledge. Hence, we choose to give you a fully functional code that requests the purchase of a book from the Flipkart website.

Contents
Required steps to add a book to the cart.Sample code to add a book to the cart.

This post is our second submission to the coding series of Selenium Webdriver exercises. We took this initiative because the right candidate needs to be good at concepts but must have a deep code-level understanding as well. Since it’s an advanced 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 posts.

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

Use Selenium to Add a Book to the cart on Flipkart

So, here is the complete code that adds a book to the cart on the 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 made sure that the code should work without any code changes. However, if you see any issue, it could most likely be an issue related to XPath. So, use <FirePath> in Firefox or <XPath Helper> in Chrome to finalize the right XPath for your web element.

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

Required steps to add a book to the cart.

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

2- Navigate to the Flipkart website and perform the 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. */
//a[contains(.,'Selenium')])[last()]

/* Select the first book from the search results. */
//a[contains(.,'Selenium')])[1]

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 the book entry, and press continue to fill the email.

Also Try: 10 Selenium Coding Problems

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 the 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;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.google.common.base.Function;

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("webdriver.chrome.driver", driverPath + "chromedriver.exe");
        // Launching Chrome browser.
        driver = new ChromeDriver();
        driver.get(URL);
        driver.manage().window().maximize();
    }

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

        initWebDriver("http://www.flipkart.com");

        flipkartLogin();

        driver.findElement(By.id(sSearchBox)).sendKeys(sBookKey);

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

        WebDriverWait wait = new WebDriverWait(driver, 30);

        wait.until(ExpectedConditions.elementToBeClickable(By.xpath(sBookName))).click();

        wait.until(ExpectedConditions.elementToBeClickable(By.xpath(sAddToCart))).click();

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

        // pause for a second and close the browser.
        Thread.sleep(1000);
        endSession();
    }

    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 > () {

            @Override
            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 {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TBD: Auto-generated catch block.
            e.printStackTrace();
        }
    }

    public static void endSession() {
        driver.close();
        driver.quit();
    }
}

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

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.

Best,

TechBeamers

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

TAGGED:Webdriver Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
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 MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article How to Use Selenium IDE - Quick Tips Selenium IDE Basics
Next Article Software Testing Interview Questions for Testers New to Software Testing? Check 20 Interview Questions

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x