Home page

Wednesday, December 11, 2019

Selenium code for Flipkart search auto populate

Code to automate Flipkart using selenium

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Flipkart {

    static WebDriver driver;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"//drivers//chromedriver.exe"); //Chrome driver location
        driver = new ChromeDriver();
        driver.manage().window().maximize(); //Maximize window
        driver.get("https://www.flipkart.com/"); //Open Flipkart
       
        if(driver.findElement(By.xpath("//button//div//following-sibling::span[contains(text(),'Login')]")).isDisplayed()) //Checking Login button to make sure if Login popup open or not
            driver.findElement(By.xpath("(//button)[2]")).click(); // Clicking close icon of login popup
       
        driver.findElement(By.name("q")).sendKeys("iPhone 7"); //Enter iPhone 7 text in search box
        driver.findElement(By.xpath("//div[contains(@class,'col-12-12 _2tVp4j')]")).click(); //Click inside search box
       
        List<WebElement> product = driver.findElements(By.xpath("//form[contains(@class,'_1WMLwI header-form-search')]//ul//li")); //Store all Auto populated values in list object.
       
        String mobileItem = "iphone 7 plus back cover"; //Item which we want to search
       
        for(WebElement element : product) {
            if(element.getText().equals(mobileItem)){ //Compare all items with mobileItem
                element.click(); //Click matching item
                break;
            }               
        }
       
        Thread.sleep(4000);
        driver.quit();

    }
   
}


2 comments: