Showing posts with label Example with Real Scenario. Show all posts
Showing posts with label Example with Real Scenario. Show all posts

Monday, May 12, 2014

How to verify BreadCrumb ?

ex- Home>Services>Enterprise Web, this kind of sequence is called as breadcrumb.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class BreadCrumb {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.etouch.net/home/index.html");
        WebElement service = driver.findElement(By.xpath("//a[text()='Services']"));
        Actions act = new Actions(driver);
        act.moveToElement(service).perform();
        driver.findElement(By.xpath("//li[a[text()='Services']]//a[text()='Enterprise Web']")).click();
       
       
        String breadcrumb = driver.findElement(By.xpath("//div[@class='breadcrumb']")).getText();
        System.out.println(breadcrumb);
       
        String lastBreadcrumb = driver.findElement(By.xpath("//div[@class='breadcrumb']/span[last()]")).getText();
        System.out.println(lastBreadcrumb);
        if(lastBreadcrumb.equals("Enterprise Web")){
            System.out.println("bread crumb is in correct order.");
        }else{
            System.out.println("bread crumb is not in correct order.");
        }
    }
}

How to scroll down and up in any web page.

Note- window.scrollBy(forUp,forDown). Here in this method forUp, you can give any value depends on how much you want to scroll up but before that you have to scroll down so that there would be some space to scroll up.
Ex-

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ScrollDown {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.flipkart.com/womens-clothing/pr?sid=2oq,c1r&otracker=hp_nmenu_sub_women_1_View%20all");
        driver.manage().window().maximize();
        JavascriptExecutor jsx = (JavascriptExecutor)driver;
        jsx.executeScript("window.scrollBy(0,4500)", "");
        Thread.sleep(3000);
        jsx.executeScript("window.scrollBy(2000,0)", "");
    }
}

How to open a link in new tab.



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class NewTab {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        Actions act = new Actions(driver);
        WebElement link = driver.findElement(By.id("gb_70"));
        act.moveToElement(link).contextClick().sendKeys("T").perform();
    }
}

How to move the pointer as well while moving the cursor or How to use Robot class.

Ans- To move the pointer with the cursor we have to use the Robot class.
Ex-

import java.awt.AWTException;
import java.awt.Robot;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Myntra {
    public static void main(String[] args) throws InterruptedException, AWTException, IOException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.navigate().to("http://www.myntra.com/");
        WebElement women = driver.findElement(By.xpath("//div[@class='head']//a[4][@href='/shop/women?src=tn&nav_id=34']"));
       
        Point coordinate = women.getLocation();
        Robot robot = new Robot();
        robot.mouseMove(coordinate.getX()+30, coordinate.getY()+120);
        Thread.sleep(10000);
        driver.findElement(By.xpath("//a[@href='/women-jeans?src=tn&nav_id=48']")).click();
        driver.findElement(By.xpath("//div[@id='login']//div[@class='close']")).click();
       
    }
}

Sunday, May 11, 2014

How to get the tooltip for all the images present in the webpage.

Note- code has been done in such a way so that it will not print those title which are blank.


import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.
WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Deepika {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.swissoutpost.com/");
        List<WebElement> imgs = driver.findElements(By.tagName("img"));
        System.out.println(imgs.size());
        int num =0;
        String toolTip="";
        for(int i=0; i<imgs.size(); i++){
            toolTip = imgs.get(i).getAttribute("title");
            num+=1;
            if(toolTip.equals("")){
            }else{
                System.out.println(toolTip);
            }
        }
        System.out.println(num);
    }
}

How to send a mail through gmail with attachment.



import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;

public class SendMailWithAttachment{
    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner kb = new Scanner(System.in);
        System.out.println("enter ur id: ");
        String id = kb.nextLine();
        System.out.println("enter ur pass: ");
        String password = kb.nextLine();
        System.out.println("enter email-id to whom u want to send the mail: ");
        String toId = kb.nextLine();
        System.out.println("enter subject for mail: ");
        String subject = kb.nextLine();
        System.out.println("enter the content of the mail: ");
        String content = kb.nextLine();
       
        //open gamil
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&hl=en&emr=1&elo=1");
       
        //login to gmail
        driver.findElement(By.id("Email")).sendKeys(id);
        driver.findElement(By.xpath("//input[@id='Passwd']")).sendKeys(password);
        driver.findElement(By.xpath("//input[@type='checkbox']")).click();
        driver.findElement(By.name("signIn")).click();
       
        //click on compose and add the to mail id, and subject
        driver.findElement(By.xpath("//div[text()='COMPOSE']")).click();
        driver.findElement(By.xpath("//form[1]//textarea[1]")).sendKeys(toId);
        driver.findElement(By.xpath("//div[@class='aoD az6']//input[@class='aoT']")).sendKeys(subject);
       
        //wirte the mail body, that mail body is under frame so 1st switch the control to frame then write
        driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@tabindex='1']")));
        driver.findElement(By.xpath("//body[@class='editable LW-avf']")).sendKeys(content);
        driver.switchTo().defaultContent(); // again switch back to main page
       
        //click on attachment
        driver.findElement(By.xpath("//div[@class='a1 aaA aMZ']")).click();
        //use autoit tool to attach a file
        Runtime.getRuntime().exec("C:\\selenium\\AutoIT\\fileUpload.exe");
        Thread.sleep(10000); //wait for 10sec to upload file
       
        //click on send
        driver.findElement(By.xpath("//div[text()='Send']")).click();
        String msg = driver.findElement(By.xpath("//div[contains(text(),'Your message has been sent.')]")).getText();
        String exp = "Your message has been sent. View message";
        Assert.assertEquals(msg, exp);
        System.out.println("pass");
        driver.close();
    }
}



Note- Here Autoit tool has been used to attach the file because by using sendKeys() method we can't upload the file in gmail. Below is the script used to upload the file thru autoit-

WinWaitActive("File Upload")
Send("path of the file")
ControlClick("","&Open","Button1")

ex- path of the file = C:\java learn\important cmd for Java.txt

How to login, get the number of mails in inbox and logout from the gmail account.


import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class InboxCount {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        System.out.println("enter ur gmail id: ");
        String id = kb.nextLine();
        System.out.println("enter ur gmail pass: ");
        String password = kb.nextLine();
       
       
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&hl=en&emr=1&elo=1");
        driver.findElement(By.id("Email")).sendKeys(id);
        driver.findElement(By.xpath("//input[@id='Passwd']")).sendKeys(password);
        driver.findElement(By.xpath("//input[@type='checkbox']")).click();
        driver.findElement(By.name("signIn")).click();
       
        String inbox = driver.findElement(By.xpath("//a[@href='https://mail.google.com/mail/u/0/#inbox']")).getText();
        System.out.println(inbox);
       
        //sign out
        driver.findElement(By.xpath("//span[@class='gb_V gbii']")).click();
        driver.findElement(By.linkText("Sign out")).click();
       
        driver.close();
       
    }
}

How to upload the file.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FileUpload {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("http://www.megafileupload.com/");
        driver.findElement(By.xpath("//input[@class='upload_txt']")).sendKeys("path of file to be uploaded");
        driver.findElement(By.cssSelector("input[id='terms']")).click();
        driver.findElement(By.cssSelector("input[name='send']")).click();
    }
}

How to find the broken link in a web page or how to determine a link is working or not.

Note- Here in place of any website i have created my webpage with broken link which i passed as url in to("url") method.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrokenLink {
    public static void main(String[] args) throws InterruptedException, IOException {
       
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.navigate().to("file:///C:/Program%20Files%20%28x86%29/sank_java/selenium/WebDriver/Selenium_web.html");
        List<WebElement> elements = driver.findElements(By.tagName("a"));
        System.out.println(elements.size());
       
        for(WebElement linkElement: elements){
            String link = linkElement.getAttribute("href");
            System.out.println(link);
            if(link!=null){
                 if(!isLink(link)){
                     continue;
                 }
            }
            verifyLinkActive(link);
        }
        driver.quit();
    }
    public static boolean isLink(String link){
       
        return link.contains("http://") ;
    }
    public static void verifyLinkActive(String linkUrl) throws IOException{
        try {
            URL url = new URL(linkUrl);
            HttpURLConnection httpURLConnect = (HttpURLConnection)url.openConnection();
            httpURLConnect.setConnectTimeout(3000);
            httpURLConnect.connect();
            if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND){
                System.out.println(linkUrl+"-"+httpURLConnect.getResponseMessage()+"-"+
            HttpURLConnection.HTTP_NOT_FOUND);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

   
}

How to open browser with Add Ons using WebDriver

Note- File extension = new File("give here the path of the Add Ons file with use you want to open browser.");

import java.io.File;
import java.io.IOException;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class AddOns {
    public static void main(String[] args) {
        File extension = new File("C:/Users/IBM_ADMIN/Documents/SametimeFileTransfers/firebug-1.12.7-fx.xpi");
        FirefoxProfile profile = new FirefoxProfile();
        try {
            profile.addExtension(extension);
        } catch (IOException e) {
            e.printStackTrace();
        }
        WebDriver driver = new FirefoxDriver(profile);
        driver.get("https://mail.google.com/mail/u/0/#inbox");
       
    }
}

Saturday, May 10, 2014

Login Logout scenario for yahoo.com

Here is the code to login and logout in yahoo.com. Here its fetching the userid and password from excel sheet.

import java.awt.AWTException;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class YahooLoginLogOut {
    public static void main(String[] args) throws AWTException, InterruptedException, InvalidFormatException, IOException {
    //get the data from excel sheet
            FileInputStream fis = new FileInputStream("./InputData.xlsx");
            Workbook wb = WorkbookFactory.create(fis);
            String emailId = wb.getSheet("Sheet2").getRow(0).getCell(0).getStringCellValue();
            String password = wb.getSheet("Sheet2").getRow(1).getCell(0).getStringCellValue();
           
            //open browser and Yahoo
            WebDriver driver = new FirefoxDriver();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.get("https://in.yahoo.com/");
            Actions act = new Actions(driver);
            //login
            act.moveToElement(driver.findElement(By.xpath("//em[text()='Sign In']"))).perform();
            driver.findElement(By.xpath("//span//a[@class='login-svc ylogin login-btn-purple rapid-noclick-resp login-btn-small']")).click();
            driver.findElement(By.id("username")).sendKeys(emailId);
            driver.findElement(By.id("passwd")).sendKeys(password);
            driver.findElement(By.xpath("//button[contains(text(),'Sign in')]")).click();
           
            //sign out
            act.moveToElement(driver.findElement(By.xpath("//img[contains(@class,'tab-icon')]"))).perform();
            driver.findElement(By.xpath("//span[text()='Sign Out']")).click();
           
            driver.close();
    }
}

Friday, May 9, 2014

How to get the test of 1st five news in Yahoo.com

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class YahooGet {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://in.yahoo.com/?p=us");
        List<WebElement> link = driver.findElements(By.xpath("//div[contains(@class,'footer-section')]//li//a"));
        for(WebElement ele: link){
            System.out.println(ele.getText());
        }
    }
}

Thursday, May 8, 2014

How to print the cart content for multiple rows. (Real scenario)

Step1- Open http://shopping.rediff.com/shopping/index.html
Step2- Go to Mobiles.
Step3- click on Mobile Handsets.
Step4- click on 1st mobile.
Step5- click on Buy now.
Step6- again go back on Mobile Handsets page and click on 2nd mobile and repeat the
           step5.
Step7. likewise repeat the step6 for rest of the mobile on Mobile Handsets page.
Step8. print all the rows from the cart.

import java.awt.AWTException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Rediff {
    public static void main(String[] args) throws AWTException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("http://shopping.rediff.com/shopping/index.html");
        WebElement mobiles = driver.findElement(By.xpath("//span[text()='Mobiles']"));
        Actions act = new Actions(driver);
        act.moveToElement(mobiles).perform();
        act.moveToElement(driver.findElement(By.xpath("//a[text()='Mobile Handsets']"))).click().perform();
       
       
        List<WebElement> sets = driver.findElements(By.xpath("//div[@class='div_grid_display_big']"));
       
        for(int i=0; i<3; i++){
            sets.get(i).findElement(By.tagName("a")).click();
            driver.findElement(By.xpath("//input[@value='Buy now']")).click();
            if(i<2){
                driver.get("http://shopping.rediff.com/categories/mobile-handsets--new-/cat-8344/?sc_cid=fixcat_mobile%20handsets");
                sets = driver.findElements(By.xpath("//div[@class='div_grid_display_big']"));
            }
        }
       
            driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@name='cartframe']")));   
           
            List<WebElement> cart = driver.findElements(By.xpath("//tr[@class='selected_graybg']//table[@style='width:800px;padding:8px 0px 0px 0px;']"));
            for(int j=0; j<cart.size(); j++){
                List<WebElement> rowstest=cart.get(j).findElements(By.tagName("tr"));
                for(WebElement r:rowstest)
                {
                    List<WebElement> cols=r.findElements(By.tagName("td"));
                    for(int k=0; k<cols.size(); k++)
                    {
                        if(k==0){
                            System.out.print(cols.get(k).findElement(By.tagName("a")).getText()+"  ");
                        }else if(k==1){
                            System.out.print(cols.get(k).findElement(By.tagName("input")).getAttribute("value")+"  ");
                        }else{
                            System.out.print(cols.get(k).getText()+"  ");
                        }   
                    }
                    System.out.println();
                }
            }
        }
       
}

How to select 1st option from all the dorpdown.


Select class can not be used always to select the option from dropdown. Select class can be used only when the dropdown menu has been created using <select> tag.
So for other scenario, 1st you can click on dropdown menu and then you can click on the particular option, either after moving the cursor over option then click or directly click on the option.

Note- Here for the 1st dropdown we can select the 1st element but for the rest the 1st element is blank so selecting the 2nd option.

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SelectFirstValueFromAllDropdown {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://regtest.gmail.co.za/#top");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        List<WebElement> ele = driver.findElements(By.xpath("//select[@class='form-input']"));
        for(int i=0; i<ele.size(); i++){
           
            Select sel = new Select(ele.get(i));
            if(i==0){
                sel.selectByIndex(0);
            }else{
                sel.selectByIndex(1);
            }
        }
        WebElement where = driver.findElement(By.xpath("//select[@id='demogscp']"));
        Select sel1 = new Select(where);
        sel1.selectByIndex(1);
        List<WebElement> date = driver.findElements(By.xpath("//td//select[contains(@id,'date')]"));
        for(int i=0; i<date.size(); i++){
            Select sel = new Select(date.get(i));
            sel.selectByIndex(0);
        }
    }
}

How to execute the same test case with multiple set of input data using @DataProvider.

How @DataProvider work-
1) The number of columns become the number of arguments of the @Test method with their respective order as they have been added while storing in Object array.
2) Once the @Test annotation found with 'dataProvider' keyword, it will call the @DataProvider method.
3) This @DataProvider method will start iterating till the time @Test method has not been executed for all the rows of excel sheet.
4) In simple word, one could say, @DataProvider call the @Test method for each iteration.


Here the @Test method will execute the number of times rows are there in the sheet. For example here is the scenario of login in Yahoo.
Step1- Open the browser and open yahoo.com
Step2- Get the 1st row data from sheet and pass that as input (userName, pass, and expTitle) and click on login button.
Step3- Get the title of the page after login and verify with expTitle.
Step4- close the browser wether testcase passed or failed.
Step4. Then again go back to step2 and get the 2nd row data likewise it will execute the test case for all the rows.


import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProvider1
{
    @Test(dataProvider="DataInput")
    public void login(String userName, String pass, String expTitle) throws InterruptedException{
        //open browser and Yahoo
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://in.yahoo.com/");
        Actions act = new Actions(driver);
        //login
        act.moveToElement(driver.findElement(By.xpath("//em[text()='Sign In']"))).perform();
        driver.findElement(By.xpath("//span//a[@class='login-svc ylogin login-btn-purple rapid-noclick-resp login-btn-small']")).click();
        driver.findElement(By.id("username")).sendKeys(userName);
        driver.findElement(By.id("passwd")).sendKeys(pass);
        driver.findElement(By.xpath("//button[contains(text(),'Sign in')]")).click();
       
        Thread.sleep(2000);
        String actTitle = driver.getTitle();
        try{
            Assert.assertEquals(actTitle, expTitle);
            driver.close();
        }catch(Exception e){
            driver.close();
        }
       
    }
    @DataProvider(name="DataInput")
    public static Iterator fetchData() throws InvalidFormatException, IOException{
        ArrayList myData = new ArrayList();
        FileInputStream fis = new FileInputStream("./InputData.xlsx");
        Workbook wb = WorkbookFactory.create(fis);
        Sheet sh = wb.getSheet("Sheet4");
        int numOfRows = sh.getLastRowNum();
        String userName, pass, expTitle;
        for(int i=0; i<numOfRows; i++){
            userName = sh.getRow(i).getCell(0).getStringCellValue();
            pass = sh.getRow(i).getCell(1).getStringCellValue();
            expTitle = sh.getRow(i).getCell(2).getStringCellValue();
            myData.add(new Object[]{userName,pass,expTitle});
        }
        return myData.iterator();
    }
}

Wednesday, May 7, 2014

Real time scenario to check item added to cart or not.

Scenario-

1. Browse and open http://www.infibeam.com as a input data from excel sheet...
2. Navigate to all stores then mobiles and select mobiles type...
3. Then enter blackberry in search box and click on search...
4. select price range 10000 to 18000...
5. select displayed mobile, and write model name and price in a Textfile....
and check the product Instock or not,if it is Instock then click on Buy Now...(write Reusable script)
6. check it is added in to the cart or not...
7. Close the Browser.

import java.io.BufferedWriter;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Siva {
public static void main(String[] args) throws InvalidFormatException, IOException{
String url = getData(0,0);
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(url);
WebElement mob = driver.findElement(By.xpath("//span[text()='Mobiles & Tablets']"));
Actions act = new Actions(driver);
act.moveToElement(mob).perform();
WebElement type = driver.findElement(By.linkText("Mobile Type"));
act.moveToElement(type).click().perform();
driver.findElement(By.id("suggest")).sendKeys("blackberry");
driver.findElement(By.xpath("//form[@id='srchForm']//input[@value='Search']")).click();
driver.findElement(By.xpath("//a[@title='10000-18000']")).click();
List<WebElement> model = driver.findElements(By.xpath("//span[@class='title']"));
List<WebElement> price = driver.findElements(By.xpath("//div[@class='price']"));
FileWriter fileWriter = new FileWriter("out.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("model "+"\t\t\t\t\t"+"price"+"\n");

for(int i=0; i<model.size(); i++){
bufferedWriter.write(model.get(i).getText()+"\t"+price.get(i).getText()+"\n");
}
bufferedWriter.close();

model.get(0).click();
driver.findElement(By.xpath("//input[@value='Buy Now']")).click();
String quantity = driver.findElement(By.xpath("//div[@class='quantity']/div")).getText();
int n = Integer.parseInt(quantity);
if(n==1){
System.out.println("phone has been added to cart");
}
driver.close();
}
public static String getData(int row, int cell) throws InvalidFormatException, IOException{
FileInputStream fis = new FileInputStream("./InputData.xlsx");
Workbook wb = WorkbookFactory.create(fis);
String value = wb.getSheet("Sheet3").getRow(row).getCell(cell).getStringCellValue();
return value;
}
}

How to save the images in a newly created folder while execution.

Note- create a folder with name Images and have InputData.xslx and just copy paste the below code and run it

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Kalai {
public static void main(String[] args) throws InvalidFormatException, IOException {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.urbanspoon.com/c/1/Seattle-restaurants.html");
driver.findElement(By.partialLinkText("City of Seattle")).click();
List<WebElement> nameOfRestros = driver.findElements(By.className("resto_name"));
int numOfRestros = nameOfRestros.size();
for(int i=0; i<numOfRestros; i++){
nameOfRestros.get(i).click();
mainProc(driver,i);
driver.get("http://www.urbanspoon.com/.../City-of-Seattle-restaurants");
nameOfRestros = driver.findElements(By.className("resto_name"));
}

driver.close();
}
public static void mainProc(WebDriver driver, int rowNum) throws InvalidFormatException, IOException{
String nameOfResto = driver.findElement(By.xpath("//h1[@itemprop='name']")).getText().trim();

boolean create = true;
writeData(rowNum, 0, nameOfResto, create);
create = false;
String phone = driver.findElement(By.xpath("//a[@class='phone tel no-link']")).getText().trim();

writeData(rowNum, 1, phone, create);
String address = driver.findElement(By.className("tags")).getText().trim();

writeData(rowNum, 2, address, create);

driver.findElement(By.linkText("View menu")).click();

List<WebElement> img = driver.findElements(By.xpath("//div[@class='list']//div[@class='image']//img"));

System.out.println(img.size());
for(int i=0; i<img.size(); i++){
String imgSrc = img.get(i).getAttribute("src");

WebElement dishEle = img.get(i).findElement(By.xpath("..")).findElement(By.xpath("..")).findElement(By.xpath("..")).findElement(By.xpath(".."));
String dishName = dishEle.findElement(By.tagName("h3")).getText();
File folder = new File("./Images/"+nameOfResto);
folder.mkdir();

String folderName = folder.getAbsolutePath();
pasteImg(folderName, imgSrc, dishName, i);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0,10000)", "");
}
}
public static void writeData(int rowNum, int cellNum, String value, boolean create) throws InvalidFormatException, IOException{
FileInputStream fis = new FileInputStream("./InputData.xlsx");
Workbook wb = WorkbookFactory.create(fis);
if(create)
wb.getSheet("Sheet3").createRow(rowNum).createCell(cellNum).setCellValue(value);
else
wb.getSheet("Sheet3").getRow(rowNum).createCell(cellNum).setCellValue(value);
FileOutputStream fos = new FileOutputStream("./InputData.xlsx");
wb.write(fos);
}
public static void pasteImg(String folderName, String imgSrc, String dishName, int i) throws IOException{
URL url = new URL(imgSrc);
BufferedImage image = ImageIO.read(url);
File file = new File(folderName+"/"+dishName+".jpg");
ImageIO.write(image,"jpg", file);
}
}