Showing posts with label advanced level real time scenario. Show all posts
Showing posts with label advanced level real time scenario. Show all posts

Wednesday, June 25, 2014

Print the name of friends with the status like one is online, busy, idle or offline in gmail chat.

Note- Please give the gmail id and password while runtime. (after pressing ctrl+f11).

import java.util.List;
import java.util.Scanner;
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.firefox.FirefoxDriver;

public class GmailOnlinePeople {

public static void main(String[] args) {
    WebDriver driver;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the gmail id: ");
    String emailId = in.next();
    System.out.println("Enter the pass: ");
    String pass = in.next();
 
    driver = new FirefoxDriver(); //open firefox browser
 
    //login to gmail
    driver.get("http://www.gmail.com");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(40,TimeUnit.SECONDS);
    driver.findElement(By.name("Email")).sendKeys(emailId);
    driver.findElement(By.name("Passwd")).sendKeys(pass);
    driver.findElement(By.name("signIn")).click();
    String name="";
    //friends with available status
    try {
        List<WebElement> available = driver.findElements(By.xpath("//tr[td[img[contains(@alt,'Available')]]]//td[2]/span[1]"));
        System.out.println("number of friends with available status in the gmail chat: "+available.size());
        if(available.size()!=0){
            System.out.println("Name of the friends with Available status: ");
        }
        for (int i=0; i <available.size(); i++)
        {
            name = available.get(i).getAttribute("textContent");
            System.out.println((i+1)+") "+name);
        }
    } catch (NoSuchElementException e) {
        System.out.println("No one is there with available status.");
    }
   
  //friends with busy status in the gmail chat
    try {
        List<WebElement> busy = driver.findElements(By.xpath("//tr[td[img[@alt='Busy']]]//td[2]/span[1]"));
        System.out.println("number of friends with busy status in the gmail chat: "+busy.size());
        if(busy.size()!=0){
            System.out.println("Name of the friends with busy status: ");
        }
        for (int i=0; i <busy.size(); i++)
        {
            name = busy.get(i).getAttribute("textContent");
            System.out.println((i+1)+") "+name);
        }
    } catch (NoSuchElementException e) {
        System.out.println("No one is with busy status.");
    }
   
  //friends with idle status
    try {
        List<WebElement> idle = driver.findElements(By.xpath("//tr[td[img[@alt='Idle']]]//td[2]/span[1]"));
        System.out.println("number of friends with idle status in the gmail chat: "+idle.size());
        if(idle.size()!=0){
            System.out.println("Name of the friends with idle status: ");
        }
        for (int i=0; i <idle.size(); i++)
        {
            name = idle.get(i).getAttribute("textContent");
            System.out.println((i+1)+") "+name);
        }
    } catch (NoSuchElementException e) {
        System.out.println("No one is with idle status.");
    }
   
  //friends with offline status
    try {
        List<WebElement> offline = driver.findElements(By.xpath("//tr[td[img[@alt='Offline']]]//td[2]/span[1]"));
        System.out.println("number of friends offline in the gmail chat: "+offline.size());
        if(offline.size()!=0){
            System.out.println("Name of the friends offline: ");
        }
        for (int i=0; i <offline.size(); i++)
        {
            name = offline.get(i).getAttribute("textContent");
            System.out.println((i+1)+") "+name);
        }
    } catch (NoSuchElementException e) {
        System.out.println("No one is offline.");
    }
    driver.close();
}
}

Sunday, June 22, 2014

How to print the dorpdown values which are hidden ?

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 MakeMyTrip {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.makemytrip.com/");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//span[input[@tabindex='4']]//a")).click();
        List<WebElement> cities = driver.findElements(By.xpath("//li[@class='ui-menu-item']"));
        System.out.println("Number of cities : "+cities.size()); //this will take only those which are visible in 1st click
        for(int i=0; i<cities.size(); i++){
            System.out.println(i+1+") city name: "+cities.get(i).getText());
        }
        driver.close();
    }
}


output-

Number of cities : 47
1) city name: New Delhi, India (DEL)
2) city name: Mumbai, India (BOM)
3) city name: Bangalore, India (BLR)
4) city name: Goa, India (GOI)
5) city name: Chennai, India (MAA)
6) city name: Kolkata, India (CCU)
7) city name: Hyderabad, India (HYD)
8) city name: Pune, India (PNQ)
9) city name: Ahmedabad, India (AMD)
10) city name: Cochin, India (COK)
11) city name: Jaipur, India (JAI)
12) city name: Dubai, UAE (DXB)
13) city name: Singapore, Singapore (SIN)
14) city name: Bangkok, Thailand (BKK)
15) city name: New York, US - All Airports (NYC)
16) city name: Kuala Lumpur, Malaysia (KUL)
17) city name: London, UK - All Airports (LON)
18) city name: Hong Kong, China (HKG)
19) city name: Doha, Qatar (DOH)
20) city name: Colombo, Sri Lanka (CMB)
21) city name: Agartala, India (IXA)
22) city name: Agatti Island, India (AGX)
23) city name: Ahmedabad, India (AMD)
24) city name: Aizawl, India (AJL)
25) city name: Allahabad, India (IXD)
26) city name: Amritsar, India (ATQ)
27) city name: Aurangabad, India (IXU)
28) city name: Bagdogra, India (IXB)
29) city name: Bangalore, India (BLR)
30) city name: Belgaum, India (IXG)
31) city name: Bellary, India (BEP)
32) city name: Bhavnagar, India (BHU)
33) city name: Bhopal, India (BHO)
34) city name: Bhubaneshwar, India (BBI)
35) city name: Bhuj, India (BHJ)
36) city name: Calicut, India (CCJ)
37) city name: Chandigarh, India (IXC)
38) city name: Chennai, India (MAA)
39) city name: Cochin, India (COK)
40) city name: Coimbatore, India (CJB)
41) city name: Dehradun, India (DED)
42) city name: Dharamshala, India (DHM)
43) city name: Dibrugarh, India (DIB)
44) city name: Dimapur, India (DMU)
45) city name: Diu, India (DIU)
46) city name: Gaya, India (GAY)
47) city name: Goa, India (GOI)

Saturday, June 21, 2014

How to select desired date from the calendar pop-up ?

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 CalenderPopUp {
   
     public static void main(String[] args) {
     int day, month, year;
   
     String futrDate = "td_"+2015+"_"+06+"_"+24; //this is the 'id' format in the calendar popup in html code, ex- id=td_2015_6_24
   
     WebDriver driver = new FirefoxDriver();
     driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
     driver.get("http://www.yatra.com/");
   
     driver.findElement(By.id("BE_flight_depart_date")).click();
     String monthYear="";
     //this loop will execute untill your required month and year will not appear in the calendar
     //here you can also pass the input from your and by making code as common
     while(!(monthYear.equals("June 2015"))){
         driver.findElement(By.xpath("//a[@class='js_btnNext sprite nextBtn']")).click(); //this will click on next button for month
         monthYear = driver.findElement(By.xpath("//span[@class='js_monthTitle']")).getText(); // this is to get the month and year from calendar pop up
     }
   
     driver.findElement(By.xpath("//td[@id='"+futrDate+"']")).click(); //this will select the date
     }
}

How to handle multiples windows if they open at different places not all together.

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

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

public class Naukari {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.naukri.com/");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //Click on Employer's Zone
        driver.findElement(By.xpath(".//*[@id='empNavM']/ul/li[1]/a")).click();
       
        switchControlToLatestWindow(driver); //switch control to Employer's Zone window
   
        driver.findElement(By.xpath("//div[@class='headbg']//a[text()='Report a Problem']")).click(); //click on 'Report a Problem'
        //this will again open a new window
        switchControlToLatestWindow(driver); //switch control to 'Report a Problem' window
       
        driver.findElement(By.xpath("//input[@name='strName']")).sendKeys("jdhjhgdjhgj1222"); //pass some value to Your name field to confirm our control is there
}
    //this is a method to switch the control to the latest opened window
    public static void switchControlToLatestWindow(WebDriver driver){
        Iterator<String> browsers = driver.getWindowHandles().iterator();
        while(browsers.hasNext()){
            driver.switchTo().window(browsers.next());
        }
    }

}

Thursday, June 19, 2014

How to execute single testcase in two different browsers parallel in single machine using TestNG.

Sample Test Case

package hello;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParallelExecution {
        @Test
        @Parameters("browserType")  // use @Parameters to pass the input through xml
        public void dummyTest(String browserType){
            WebDriver driver;
            if(browserType.equals("FF")){
                driver= new FirefoxDriver();
                driver.quit();
            }else if(browserType.equals("IE")){
                System.setProperty("webdriver.ie.driver", "./Drivers/IEDriverServer.exe");
                driver = new InternetExplorerDriver();
                driver.quit();
            }
     }
}


testng.xml

<suite name="Suite" parallel="tests" thread-count="2"> //here parallel="tests" means run both the test in parallel and thread-count="2" means run two test cases parallel. 
  <test name="Test1">
  <parameter name="browserType" value="FF" />  //to pass the input to the java class
   <classes>
          <class name="hello.ParallelExecution"/>   //here hello is package name and ParallelExecution is class name
   </classes>
  </test>
  <test name="Test2">
  <parameter name="browserType" value="IE" />
   <classes>
          <class name="hello.ParallelExecution"/> //here hello is package name and ParallelExecution is class name
   </classes>
  </test>
</suite> 

Wednesday, June 18, 2014

Using not() in XPath. (ex- you want to write the xpath for the element whose class is not equal to 'abc').

Requirement-
In the below html code, we have to write the xpath for the span (high lighted in green color) tags present inside td tags where td class="closeTrigger" and tr class is not "week-selected".

HTML code-

<tr>
<td class="weekend closeTrigger">
<span>5</span></td>
<td class="closeTrigger">
<span>6</span></td>
<td class="closeTrigger">
<span>7</span></td>
<td class="closeTrigger">
<span>8</span></td>
<td class="closeTrigger">
<span>9</span></td>
<td class="closeTrigger">
<span>10</span></td>
<td class="weekend closeTrigger">
</tr>
<tr class="week-selected">
<td class="weekend closeTrigger date-selected">
<span>11</span></td>
<td class="closeTrigger">
<span>12</span></td>
<td class="closeTrigger">
<span>13</span></td>
<td class="closeTrigger todays-date">
<span>14</span></td>
<td class="closeTrigger">
<span>15</span></td>
<td class="closeTrigger">
<span>16</span></td>
<td class="weekend closeTrigger">
</tr>
<tr>
<td class="weekend closeTrigger">
<span>17</span></td>
<td class="closeTrigger">
<span>18</span></td>
<td class="closeTrigger">
<span>19</span></td>
<td class="closeTrigger">
<span>20</span></td>
<td class="closeTrigger">
<span>21</span></td>
<td class="closeTrigger">
<span>22</span></td>
<td class="weekend closeTrigger">
</tr>


Correct xpath- //tr[not(@class='week-selected')]//td[@class='closeTrigger']//span

For reference, here is the verified snapshot from firepath.




webpage-

Login to http://www.makemytrip.com/

Note- Here we need to take care while writing the xpath for password field because that has some hidden html code.

import java.util.concurrent.TimeUnit;

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

public class SuccessLogin{
public static void main(String[] args){

WebDriver driver =new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.makemytrip.com");
driver.findElement(By.id("login_dropOpenItem")).click();
driver.findElement(By.id("username")).sendKeys("rishi.vg1@gmail.com");
driver.findElement(By.xpath("//input[@id='password_text']")).sendKeys("somepassword");
driver.findElement(By.id("login_btn")).click();
}
}

Tuesday, June 17, 2014

Select value from dropdown without using Select class. Good example.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class SelectFromDropDown {
    public static void main(String[] args) {
        WebDriver driver=new FirefoxDriver();
        driver.get("https://makemytrip.com/");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//div//span[2][contains(@class,'flL travelers rght_space room_sec1')]")).click();
        Actions act = new Actions(driver);
        act.sendKeys(Keys.chord(Keys.DOWN,Keys.DOWN)).perform(); //press down key two times to select 3
    }
}

Monday, June 16, 2014

Print the name of the people in the gmail chatbox list and number of people in the gmail chat box in lefthand side. Realtime scenario.

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;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class GmailChatBox {
  
WebDriver driver;

@BeforeTest
public void openurl()throws InterruptedException
{
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the gmail id: ");
    String emailId = in.next();
    System.out.println("Enter the pass: ");
    String pass = in.next();
  
    driver = new FirefoxDriver(); //open firefox browser
  
    //login to gmail
    driver.get("http://www.gmail.com");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(40,TimeUnit.SECONDS);
    driver.findElement(By.name("Email")).sendKeys(emailId);
    driver.findElement(By.name("Passwd")).sendKeys(pass);
    driver.findElement(By.name("signIn")).click();
}
@Test
public void chatlist() throws InterruptedException
{
    List<WebElement> chatboxsize = driver.findElements(By.xpath("//table[@class='vH']/tbody"));
    System.out.println("number of people in the gmail chat: "+chatboxsize.size());
    String name="";
    for (int i=1; i <=chatboxsize.size(); i++)
    {
        name = driver.findElement(By.xpath("//table[@class='vH']/tbody["+i+"]/tr[1]//span[1]")).getAttribute("textContent");
        System.out.println(name);
    }
}
@AfterTest
public void closeBrowser(){
    driver.close();
}
}

Thursday, June 12, 2014

How to Select Last value from the WebList without using getOptions() ?

WebElement dropDown = driver.findElement(By.xpath("//select")); //xpath of dropdown may be different, here just giving example

Select sel = new Select(dropDown);
List<WebElement> options = driver.findElements(By.xpath("//select//options"));
int numOfOptions = options.size();
sel.selectByIndex(numOfOptions-1); //this will select last value from the dropdown but this logic will work when html code has been developed with select tag

Tuesday, June 10, 2014

How to check whether the selectbox is singleListbox or multipleListBox.

Monday, June 9, 2014

How to get the text which is not visible in web page but it is there in HTML code ? And how to check whether check box is enabled or not ?

Note: use  getAttribute("textContent") method to get the hidden text.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Facebook {
    public static void main(String[] args) {
    WebDriver driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    driver.get("https://www.facebook.com/");
    String value= driver.findElement(By.xpath("//a[@title='Go to Facebook Home']")).getAttribute("textContent");
    System.out.println("Value is : " + value);
    boolean box= driver.findElement(By.xpath("//input[@type='checkbox']")).isEnabled();
    System.out.println(box);
    driver.close();
    }
}

Wednesday, June 4, 2014

How to clear the text from the text box without using clear() method.

There could be many ways to do this.

1) Use Control+a then backspace-

Example-

import java.util.Scanner;

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

public class Clear {
    public static void main(String[] args) throws InterruptedException {
        Scanner in = new Scanner(System.in);
        System.out.println("enter the string which you want to send and then clean");
        String input = in.next();
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.co.in/?gfe_rd=cr&ei=zQmQU9D3OoyK8QfpxoDQBA&gws_rd=ssl");
        WebElement box = driver.findElement(By.name("q"));
        box.sendKeys(input);
        Thread.sleep(5000); //simply wait to see that input string has been sent to box
       
        //this for block is used to clear the input from box
        //this we can do by using clear method but clear sometime won't work so use this way
        //box.clear();
        box.sendKeys(Keys.chord(Keys.CONTROL,"a"));
        box.sendKeys(Keys.BACK_SPACE);
    }
}   

2) Press the backspace key but here the number of times backspace key pressed should be equal to the number of character in the string because backspace will clear one character in one press.

import java.util.Scanner;

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

public class Clear {
    public static void main(String[] args) throws InterruptedException {
        Scanner in = new Scanner(System.in);
        System.out.println("enter the string which you want to send and then clean");
        String input = in.next();
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.co.in/?gfe_rd=cr&ei=zQmQU9D3OoyK8QfpxoDQBA&gws_rd=ssl");
        WebElement box = driver.findElement(By.name("q"));
        box.sendKeys(input);
        Thread.sleep(5000); //simply wait to see that input string has been sent to box
      
        //this for block is used to clear the input from box
        //this we can do by using clear method but clear sometime won't work so use this way
        //box.clear();
        for(int i=0; i<input.length();i++){
            box.sendKeys(Keys.BACK_SPACE);
        }
    }
}  


Tuesday, June 3, 2014

Switch to window then frame then again switch back to frame and window. (complex example)

Note- Please do the manual steps first and see how the flow going then try with the script.
Manual Steps-
1) open google
2) type in search box 'times of india'
3) click on 1st link of 'times of india'
4) click on 'click here to go to timesofindia.com'
5) click on 'Login' button (which is in the top just beside the LogIn with Facebook)
6) click on facebook
7) check the checkbox in facebook page and click on cancle
8) then close the frame (which has 3 options facebook, twitter and your email)
9) click on india in main page.
10) close the browser.

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

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


public class TimesOfIndia {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.MINUTES);
        driver.get("https://www.google.co.in/"); //open google
        driver.findElement(By.id("gbqfq")).sendKeys("times of india"); //type in search box 'times of india'
        driver.findElement(By.xpath("//span[text()='times of india']")).click(); //click on 1st link of 'times of india'
        driver.findElement(By.xpath("//div[div[div[div[cite[b[text()='indiatimes']]]]]]//a[text()='The ']")).click(); //click on 'click here to go to timesofindia.com'
        driver.findElement(By.linkText("Log In")).click(); //click on 'Login' button
        driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@id='signupsso']"))); //now switch to login frame which has 3 options facebook, twitter and your email
        driver.findElement(By.id("fb")).click(); //click on facebook which will open in new window
        Iterator<String> it = driver.getWindowHandles().iterator();// get the address of all the windows
        String times = it.next();
        String fb = it.next();
        driver.switchTo().window(fb); // switch to facebook window
        driver.findElement(By.xpath("//input[@type='checkbox']")).click(); //check the checkbox in facebook window
        driver.findElement(By.xpath("//input[@value='Cancel']")).click(); //click on cancle button in facebook window
        driver.switchTo().window(times); //switch back to main window
        driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@id='signupsso']"))); //again switch to login frame which has 3 options facebook, twitter and your email
        Thread.sleep(2000);
        driver.findElement(By.xpath("//img[@src='/photo/11509366.cms']")).click(); // click on cross sign to close frame
        Thread.sleep(2000);
        driver.switchTo().defaultContent(); //switch back to main page
        driver.findElement(By.xpath("//div[ul[script[text()='sectionid=4719157']]]//a[@href='/india/indiaarticlelist/-2128936835.cms']")).click(); //click on india
        driver.close();
    }

}

switch to window then frame.

Note- This is to login for HDFC credit card.

import java.util.Iterator;
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;

public class HdfcBank {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("give your hdfc credit card userid: ");
        String userid = in.next();
        System.out.println("give your pass: ");
        String pass = in.next();
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("http://www.hdfcbank.com/");
        driver.findElement(By.xpath("//img[@src='/assets/images/login_butn.png']")).click();
        Iterator<String> browser = driver.getWindowHandles().iterator();
        String parent = browser.next();
        String child1 = browser.next();
     
        driver.switchTo().window(child1);
        driver.findElement(By.xpath("//img[@src='/assets/images/netbanking_continue_red.gif']")).click();
        driver.switchTo().frame(driver.findElement(By.xpath("//frame[@src='RSLogin.html']")));
        driver.findElement(By.xpath("//p[strong[text()='Credit Cardholders']]//a[text()='click here']")).click();
     
        Iterator<String> browser1 = driver.getWindowHandles().iterator();
        String child2=null;
        while(browser1.hasNext())
        {
             child2 = browser1.next();
        }
        driver.switchTo().window(child2);
        driver.findElement(By.xpath("//input[@name='fldLoginUserId']")).sendKeys(userid);
        driver.findElement(By.xpath("//input[@type='password']")).sendKeys(pass);
        driver.findElement(By.xpath("//img[@alt='Log In']")).click();
    }

}

Monday, June 2, 2014

Print the menu and submenu option of espncricinfo.com

Note- Please refer this example only when you have very good understanding of writing xpath.

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 PrintMenuAndSubMenu {
   
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       
        driver.get("http://www.espncricinfo.com/");
        List<WebElement> mainMenu = driver.findElements(By.xpath("//div[@id='mainNav']//td[contains(@class,'nav')]/a")); //this will return all the main menu options total 15 from home button to Mobile
        Actions act = new Actions(driver);
       
        for(int i=1; i<mainMenu.size(); i++){ //here i has been initialized from 1 because we want to print from Series till Mobile
            String mainMenuName = mainMenu.get(i).getText();
            System.out.println("Main Menu Name- "+mainMenuName);
            String xpath = "//div[@id='mainNav']//td[contains(@class,'nav')][a[text()='"+mainMenuName+"']]"; //here xpath has been written for independent element of submenu so used []
               
            act.moveToElement(mainMenu.get(i)).perform(); //move the cursor over main menu , like over series sothat submenu will be visible
            Thread.sleep(2000);    //to get all the submenu in list
            List<WebElement> subMenuItems = driver.findElements(By.xpath(xpath+"//a[@class='PopupLinks']"));
            int sizeOfSubMenu = subMenuItems.size();
            //System.out.println("Number of submenu items:"+ subMenuItems.size());
            System.out.print("Submenu options of "+mainMenuName+" are: ");
            if(sizeOfSubMenu==0){
                System.out.print("There is no submenu option under "+mainMenuName);
            }
            //below for loop is to print submenu
            for(int j=0; j<sizeOfSubMenu; j++){
                System.out.print(j+")"+subMenuItems.get(j).getText()+", ");
               
                if(mainMenuName.equals("Features") && j==0){
                    List<WebElement> subMenuOptions = driver.findElements(By.xpath(xpath+"//span"));
                    //this loop is to print "Features" menu three options Regulars, Highlights and Opinion
                    for(int k=0; k<subMenuOptions.size(); k++){
                        j++;
                        System.out.print(j+")"+subMenuOptions.get(k).getText()+", ");
                    }
                    j=36;
             }
            }
            System.out.println();
            System.out.println("==============================================================================");
       
    }
        driver.quit();
}
}

Wednesday, May 7, 2014

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);
}
}