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.
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.
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