Pages

Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Monday, June 18, 2018

Selenium WebDriver - Read and Write data from Excel for Gmail Login and Logout

Using Apache POI Jar file.
Apache POI Jar Files Used for this program :  ( Please download latest version )
poi 3.17.jar,
poi-examples-3.17.jar,
poi-excelant-3.17.jar,
poi-ooxml-3.17.jar,
poi-ooxml-schemas-3.17.jar,
poi-scratchpad-3.17.jar.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;


public class WriteExcel {
    WebDriver d;
    @Test
    public void testDataImport()throws Exception
    {
        d.get("https://www.gmail.com");
        d.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        d.findElement(By.linkText("SIGN IN")).click();
        WebDriverWait wait = new WebDriverWait(d, 60);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.name("identifier")));
        d.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        //Read data from excel
        FileInputStream fis=new FileInputStream("D:\\test.xlsx");
        XSSFWorkbook wb=new XSSFWorkbook(fis);
        XSSFSheet s=wb.getSheetAt(0);
       
        String data;
        for(int i=0;i<s.getLastRowNum()+1;i++)
        {
            String username = s.getRow(i).getCell(0).getStringCellValue();
            String password = s.getRow(i).getCell(1).getStringCellValue();
            d.findElement(By.name("identifier")).sendKeys(username);
            d.findElement(By.id("identifierNext")).click();
            d.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
            Thread.sleep(4000);
            Row dataRow = s.createRow(i);
            if(d.findElement(By.xpath("//div[contains(@class,'dEOOab RxsGPe')]")).isDisplayed()){
                System.out.println("Given User Name is wrong");
                screenshot(d, "Emailwrong");
                d.findElement(By.name("identifier")).clear();
                data="fail";
                if(data=="fail") {
                    dataRow.createCell(0).setCellValue(username);
                    dataRow.createCell(1).setCellValue(password);
                    dataRow.createCell(2).setCellValue("Fail");
                }
            }else {
                d.findElement(By.name("password")).sendKeys(password);
                d.findElement(By.id("passwordNext")).click();
                d.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
                Thread.sleep(4000);
                try {
                    if(d.findElement(By.xpath("//a[contains(@class,'gb_b gb_ib gb_R')]")).isDisplayed()){
                        String currenturl = d.getCurrentUrl();
                        System.out.println(currenturl);
                        screenshot(d, "inbox");
                        d.findElement(By.xpath("//a[contains(@class,'gb_b gb_ib gb_R')]")).click();
                        Thread.sleep(2000);
                        d.findElement(By.id("gb_71")).click();
                        d.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
                        Thread.sleep(2000);
                        /*d.findElement(By.xpath("//a[@id='account-chooser-link']")).click();
                    Thread.sleep(2000);
                    d.findElement(By.xpath("//a[@id='account-chooser-add-account']")).click();
                    Thread.sleep(2000);*/
                       
                        d.findElement(By.xpath("//div[contains(@class,'a9cric')]")).click();
                        Thread.sleep(2000);
                        d.findElement(By.xpath("//button[contains(@class,'q4UYxb')]")).click();
                        Thread.sleep(2000);
                        d.findElement(By.xpath("//div[contains(@class,'k6Zj8d asG8Cb')]")).click();
                        Thread.sleep(3000);
                        d.findElement(By.xpath("//div[starts-with(@class,'tk3N6e-LgbsSe-n2to0e')][1]")).click();
                        //d.findElement(By.xpath("//div[contains(@class,'tk3N6e-LgbsSe-n2to0e x81T2e tk3N6e-LgbsSe-ZmdkE tk3N6e-LgbsSe-JbbQac-i5vt6e')]")).click();
                        Thread.sleep(2000);
                        data="pass";
                        if(data=="pass") {
                            dataRow.createCell(0).setCellValue(username);
                            dataRow.createCell(1).setCellValue(password);
                            dataRow.createCell(2).setCellValue("Pass");
                        }
                    }
                }catch(Exception e) {
                    System.out.println("Given Password is wrong");
                    screenshot(d, "passwordwrong");
                    d.findElement(By.xpath("//div[contains(@class,'a9cric')]")).click();
                    Thread.sleep(2000);
                    d.findElement(By.name("identifier")).clear();
                    d.navigate().refresh();
                    d.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
                    data="fail";
                    if(data=="fail") {
                        dataRow.createCell(0).setCellValue(username);
                        dataRow.createCell(1).setCellValue(password);
                        dataRow.createCell(2).setCellValue("Fail");
                    }
                }
            }
           
        }
        try {
            FileOutputStream out =  new FileOutputStream(new File("D:\\test.xlsx"));
            wb.write(out);
            out.close();
            System.out.println("Excel with foumula cells written successfully");
             
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Thread.sleep(1000);
    }
   

@BeforeMethod
    public void setUp()
    {
        // Launch browser - check browser driver exe file location in your system
        /*System.setProperty("webdriver.gecko.driver", "D:\\browsers\\geckodriver.exe");
        d = new FirefoxDriver();*/
        System.setProperty("webdriver.chrome.driver", "D:\\browsers\\chromedriver.exe");
        d=new ChromeDriver();
        d.manage().window().maximize();
        d.manage().deleteAllCookies();
        d.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        d.manage().timeouts().pageLoadTimeout(3,TimeUnit.MINUTES);
    }
   

@AfterMethod
    public void tearDown()
    {
        // Close browser
        d.quit();
    }
   
    public void screenshot(WebDriver d, String filename) {
        File srcfile = ((TakesScreenshot)d).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(srcfile, new File("D:\\"+filename+".png"));
        }catch(Exception e) {
            e.printStackTrace();
        }
       
    }

}

Monday, October 20, 2014

Handling iframes through Web driver

 // Switch to iframe section
driver.switchTo().frame(driver.findElement(By.id("iframe id")));

// Pass the values to iframe object
 driver.findElement(By.tagName("body")).sendKeys("hi i am entering values in iframe object");

//Switch to normal content on the page.
driver.switchTo().defaultContent();

Thursday, June 21, 2012

Retriving Data from Excel Sheet with TestNG DataProvider for Selenium Webdriver.

How to get Data from Excel Sheet By Using TestNG - Data Provider for Selenium WebDriver.
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;


Public Class Registration
{
    @Test(dataProvider="Registrationdata")
    public void Registration_data(String parameter1,String parameter2,...String Parameter n)throws  Exception
  {
         // Test code
   }


    @DataProvider
    public Object[][] Registrationdata() throws Exception
    {
          Object[][] testObjArray = getTableArray("C:\\Users\\TS\\Desktop\\PatientIDlist.xlsx","Sheet1");
         return (testObjArray);
    }


    public static Object[][] getTableArray(String xlFilePath, String sheetName)    throws Exception
        {  
           String[][] tabArray = null;
           try
           {
               FileInputStream file = new FileInputStream(new File(xlFilePath));
               XSSFWorkbook workbook = new XSSFWorkbook(file);
               XSSFSheet sheet = workbook.getSheetAt(0);
               int startRow = 1;
               int startCol = 0;
               int ci,cj;
               int totalRows = 0;
               int totalCols =  0;
               totalRows = sheet.getLastRowNum();
               totalCols = sheet.getRow(0).getLastCellNum();
               System.out.println("total cols = " + totalCols);
               System.out.println("total rows = " + totalRows);
               tabArray = new String[totalRows][totalCols];
               ci=0;
               for (int i=startRow;i<=totalRows;i++,ci++)
               {
                   cj=0;
                   for (int j=startCol;j<totalCols;j++, cj++)
                   {
                       tabArray[ci][cj]=sheet.getRow(i).getCell(j).getStringCellValue();
                       System.out.println(tabArray[ci][cj]);
                   }
               }

               workbook.close();
            }
            catch (FileNotFoundException e)
            {
                System.out.println("Could not read the Excel sheet");
                e.printStackTrace();
            }
            catch (IOException e)
            {
                System.out.println("Could not read the Excel sheet");
                e.printStackTrace();
            }
            return(tabArray);
        }

}

Friday, April 6, 2012

How to Add TestNG Plug-in to Eclipse for Selenium

Adding TestNG Plug-in to Eclipse for Selenium.


·         Run Eclipse.exe.
·         In Eclipse, Click at Help Tab in Menu bar.
·         In Help Tab Click at Install New Software. (Help -> Install New Software)
·         In Install window, Click Add button which is besides Work with Text Field.
·         In Add Repository Window, in Name field enter the Value TestNG and give the URL of the   TestNG Eclipse plug-in (http://beust.com/eclipse ) in Location field.
·         Click OK button.
·         Check the TestNG check box.
·         Click NEXT Button.
·         Again Click the NEXT Button.
·         Click Radio Button for I accept the term of the license agreement.
·         Click Finish Button.
·          It shows the Installing software Window after completion Restart Eclipse.
·         Add TestNG Jar file to the Eclipse. To add Jar file, download it from given URL.
·         Click this link you can get the TestNG Eclipse Jar file. http://testng.org/testng-eclipse-6.1.1.20110718_1435.zip
·         Unzip and Add the Jar file at Build path Libraries of the Project.
  • In BuildPath click at Configure BuildPath after  click at Libraries -> Click Add Library 
  • click at Junit and Click Next Button. Select Junit4 and Click Finish Button.
  • Click at TestNG and Click Next Button and Click finish Button.
  • Check Junit4 and TestNG libraries added at Libraries.
·         Restart the Eclipse
·         You can find, it was installed or not?   In Run -> Run As -> TestNG Test.

    Friday, March 16, 2012

    Getting ToolTip Text of Yahoo Image through selenium RC


    public class tooltip
     {
    public static void main(String[] args)throws Exception
    {
    DefaultSelenium selenium = new DefaultSelenium("localhost", 4444, "*firefox","http://");
    selenium.start();
    selenium.windowMaximize();
    selenium.open("http://www.yahoomail.com");
    selenium.waitForPageToLoad("50000");
    Thread.sleep(2000);
    selenium.click("link=Yahoo!");
    Thread.sleep(5000);
    String tooltip = selenium.getAttribute("xpath=id('y-     col1')/x:div[3]/x:div/x:div/x:div/x:div/x:h2/x:a/x:img/@title");
    System.out.println("Tool tip Image title in yahoo is: "+tooltip);
    selenium.close();
    }

    }

    Monday, February 13, 2012

    Getting ToolTip Text of Google Image through selenium RC


    public class test1
    {
        public static void main(String[] args)throws Exception
        {
            DefaultSelenium selenium = new DefaultSelenium("localhost",4444,"*firefox","http://");
            selenium.start();
            selenium.windowMaximize();
             // Google Image
            selenium.open("www.google.com");
            Thread.sleep(3000);
            String tooltip = selenium.getAttribute("xpath=id('hplogo')/@title"); //At Google Logo
            System.out.println("Tool Tip Name: "+tooltip);
        }
    }

    Saturday, October 8, 2011

    Selenium RC Configuration in Eclipse


    Selenium RC (Java) Configuration:
    Steps for Configuration:
    1.  Before Configure the Selenium RC we can verify Downloaded software’s having the all the related software’s or not. To Install Selenium RC verify below Software’s
    ·         Selenium RC Jar Files  Download from www.seleniumhq.org/download/
    ·         JDK (Java Development kit) or  Net Beans or JRE
    ·         Eclipse SDK
    2.       Install JDK or JRE in your pc for before Run Eclipse.

    3.       Copy the Eclipse from selenium dump or downloaded files from Net into a Desired folder like   (in D: / or E :/) in your pc.

    4.       Create a folder with the name selenium_framework.

    5.       Create a sub folder with the name “Lib” Under selenium_framework folder.

    6.       Copy the Selenium jar files from Lib at selenium dump or from downloaded area   and paste these Selenium jar files into Lib under Selenium_ Framework.

    7.       Copy the JDK 1.5.0.11 file from the below path  c:/program files/java   and Paste it in  Selenium_framework.
    8.       Open the Eclipse in Desired folder in that Click symbol Eclipse. Exe   for installing source file for Selenium RC and click on “Ok” at Eclipse work launcher. Remember work location.

    The above showing path is workspace for Selenium RC, where the Test script is saved.
      
    9.       Click on Workbench it will allow you to move into the Eclipse.

    10.   Go to File à New àSelect java project.

    11.   Give the project Name (selenium_ automation like…) in Project Name text field.

    12.   Click on Configure JRE and Click on Add button and click on Next Button.

    13.   Select the JDK or JRE from the Selenium_framework folder by using directory Option.

    14.   Click on finish and click on ok and click ok again.

    15.   Click on Project Name (selenium_automation), right click on the JRE System Library, Click on Build path and select configure build path.

    16.   Click on Add External Jars and select Selenium jar files from the selenium_framework folder and click on “OK”.

    17.   Go to Run in Java Eclipse SDK, click on External Tools à Select External Tools configuration.

    18.   Double click on the Program which is available at Left side. Give the Server name as Selenium_server Like….  Under Name field.

    19.   Location Field: Click on the Browse File system Against Location and Select Java.exe from the below path Folder name/Selenium_framework/JDK or JRE/bin/java.exe

    20.   Working Directory Field: Click on the Browse File system and Select the Lib folder from under selenium_framework folder.   Selenium_framework/Lib

    21.   Give the arguments as in argument field like below.                                                                                                        -jar selenium-server-standalone-version number.jar (Default)                                                                                                                                                                                          (or)                                                                                                                    
        -jar selenium-server-standalone-version number.jar -port1234   (If already port number available in your system). 

    22.   Click Run server icon in Java –Project Name/src. Check application working correctly or not in Console. (How to know without any error message and showing given port number or default port number is 4444).

    23.   Now you can create the classes from New à Class and select Public Static void main(string [] args) and Click OK.

    24.   Now you can develop Script .

    25.  You Can Create All Test Scripts or Some important scripts as one package for ex...  Admin Suite, Staff Suite likes ….Under Your Project Name. To Create Package Right Click at Your Project Name and New à  Package. In this Package You can put Suitable scripts.

                                                                                                                                

    Wednesday, April 27, 2011

    Selenium vs. QTP


    Selenium:
    1.       Selenium is an Open source tool.
    2.       It supports the scripting languages HTML, Java, PHP, Perl, Python, Ruby, .Net(c#) …
    3.       It supports the many Browsers like Firefox, Internet Explorer, Safari, Google chrome, Opera…
    4.       It supports the many Operating systems like Windows, Linux, and MAC ….
    5.       It tests (or) supports  only Web Applications
    6.       It is Flexible and Extensible.

    QTP:
    1.       QTP is not an open source tool and It is Costly.
    2.       It supports the only VB Scripting Language.
    3.       It works on only Internet Explorer Browser.
    4.       It works on only Windows Operating System.
    5.       It tests both client and Web Applications.
    6.       It is Flexible.

    Saturday, March 26, 2011

    what is Selenium?

     Selenium:

    • Test tool for web applications
    • Runs in any mainstream browser
    • Supports tests in many languages
    • Selenese (pure HTML, no backend required)
    • Java, C#, Perl, Python, Ruby
    • Record/playback (Selenium IDE)
    • Open Source with corporate backing
    • Lives at selenium.openqa.org.

    Selenium Uses:

     • Use Selenium when it makes sense
    • when you want to reproduce a user’s interaction with your application in a real web browser
    • when you depend on the browser (AJAX)
    • Do consider presentation model and HTTPUnit
    • Use Selenium for Integration Testing
    • Use Selenium in your development environment
    • Use the features offered by your language

    A few Selenese commands:

    Click,  Close, CreateCookie, dragdrop, fireEvent, getEval, getHtmlSource, , getTitle, getValue
    goBack, isElementPresent, isTextPresent, isVisible, ,keyPress, mouseOver, open, refresh, type

    The most commonly used commands for building tests:
    Open:   opens a page using a URL.
    click/clickAndWait:  performs a click operation, and optionally waits for a new page to load.
    verifyTitle/assertTitle:   verifies an expected page title.
    verifyTextPresent:   verifies expected text is somewhere on the page.
    verifyElementPresent:  verifies an expected UI element, as defined by its HTML tag, is present on the page.
    verifyText:  verifies expected text and it’s corresponding HTML tag are present on the page.
    verifyTable:  verifies a table’s expected contents.
    waitForPageToLoad:  pauses execution until an expected new page loads. Called automatically  when clickAndWait is used.
    waitForElementPresent:  pauses execution until an expected UI element, as defined by its HTML tag, is present on the page.

    Data Driven Testing using Selenium and TestNG