Excel数据未填充到Web表单中

时间:2019-02-12 15:04:33

标签: java selenium

我有一个查询,我确实需要从xsls读取数据并通过selenium Web驱动程序将内容填充到Web表单中,但是当我这样做时,在Web表单中不是填充我的数据,而是它显示“行2或xls中不存在Addressline1列”,这是在我的Web表单中填充的数据,这是下面的代码

package com.DatadriveTest;

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

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.excel.utility.Testutil;

public class Readxldatatocards
{

    WebDriver driver;

    @BeforeMethod

        public void setup() {

        System.setProperty( "webdriver.chrome.driver","D:\\chromedriver.exe" );
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().pageLoadTimeout( 20, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait( 20, TimeUnit.SECONDS);

        driver.get("http://mt-bun-app02:9080/CMSBackOffice/cardtype");


    }

    @DataProvider

    public Iterator<Object[]> getTestData(){
       ArrayList<Object[]> testData= Testutil.getDataFromExcel();
       return testData.iterator();
   }




    @Test(dataProvider="getTestData")

    public void CardRegTest(String Title, String Surname, String Forename, String Gender, String DateofBirth, String Addressline1, String Addressline2,
            String Postcode, String DisabilityStatus, String Disabilityduration, String Medicaldate) {

        //Enter data

        driver.findElement(By.id("username")).sendKeys("ZAMEER");
        driver.findElement(By.id("password")).sendKeys("Password2019");
        driver.findElement(By.id("actionLogon")).click();

        driver.findElement(By.xpath("//div[@class='bottom']/a[@href='addnewcardholder'][contains(text(),'Add new customer')]")).click();

        Select select = new Select(driver.findElement(By.xpath("//select[@id='customerTitle']")));
        select.selectByVisibleText("Mr");

        driver.findElement( By.xpath("//input[@id='customerSurname']")).clear();
        driver.findElement( By.xpath("//input[@id='customerSurname']")).sendKeys(Surname);


        driver.findElement(By.xpath("//input[@id='customerForename']")).clear();
        driver.findElement(By.xpath("//input[@id='customerForename']")).sendKeys(Forename);

        driver.findElement(By.xpath("//p[@class='genderTable field']//span[1]//input[1]")).click();

        driver.findElement(By.xpath("//input[@id='customerDob']")).clear();
        driver.findElement(By.xpath("//input[@id='customerDob']")).sendKeys(DateofBirth);

        driver.findElement(By.xpath("//input[@id='locationAddress1']")).clear();
        driver.findElement(By.xpath("//input[@id='locationAddress1']")).sendKeys(Addressline1);

        driver.findElement(By.xpath("//input[@id='locationAddress2']")).clear();
        driver.findElement(By.xpath("//input[@id='locationAddress2']")).sendKeys(Addressline2);

        driver.findElement(By.xpath("//input[@id='locationAddrPostcode']")).clear();
        driver.findElement(By.xpath("//input[@id='locationAddrPostcode']")).sendKeys(Postcode);

        Select select1 = new Select(driver.findElement(By.xpath("//select[@name='customerDisability']")));
        select1.selectByVisibleText("Severe Walking Disability");

        Select select2= new Select(driver.findElement(By.xpath("//select[@name='Disability duration']")));
        select2.selectByVisibleText("1 Year");

        driver.findElement( By.xpath("//input[@name='customerMedical']")).clear();
        driver.findElement( By.xpath("//input[@name='customerMedical']")).sendKeys( Medicaldate);

        //upload photo image
        driver.findElement(By.xpath("//input[@id='photoImage']")).click();

        WebElement UploadImg = driver.findElement(By.xpath("//input[@id='photoImage']"));
        UploadImg.sendKeys("D:\\Tulips.jpg");

        driver.findElement(By.xpath("//input[@id='actionUpload']")).click();
        driver.findElement(By.xpath("//img[@id='Accept']")).click();
    }


    @AfterMethod

    public void teardown() {
        driver.quit();
    }

}

这里是excel实用程序类

package com.excel.utility;

import java.util.ArrayList;

public class Testutil
{
    static Xls_Reader reader;

    public static ArrayList<Object[]> getDataFromExcel(){

        ArrayList<Object[]> myData = new ArrayList<Object[]>();

        try {
            reader = new Xls_Reader("D://Merseytravelezamples.xlsx");
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int rowNum =2; rowNum <= reader.getRowCount("Sheet1"); rowNum++) {

            String Title = reader.getCellData("Sheet1","Title", rowNum);
            String Surname = reader.getCellData("Sheet1", "Surname", rowNum);
            String Forename = reader.getCellData("Sheet1", "Forename", rowNum);
            String Gender = reader.getCellData("Sheet1", "Gender", rowNum);
            String DateofBirth = reader.getCellData("Sheet1", "Date of Birth", rowNum);
            String Addressline1 = reader.getCellData("Sheet1", "Addressline1", rowNum);
            String Addressline2 = reader.getCellData("Sheet1", "Addressline2", rowNum);
            String Postcode = reader.getCellData("Sheet1", "Postcode", rowNum);
            String Disabilitystatus = reader.getCellData("Sheet1", "Disabilitystatus", rowNum);
            String Disabilityduration = reader.getCellData("Sheet1", "Disabilityduration", rowNum);
            String Medicaldate = reader.getCellData("Sheet1", "Medicaldate", rowNum);


            Object ob[] = {Title, Surname, Forename, Gender, DateofBirth, Addressline1, Addressline2, Postcode, Disabilitystatus, Disabilityduration, Medicaldate };
            myData.add(ob);
        }

        return myData;


    }





}

1 个答案:

答案 0 :(得分:0)

根据讨论,您没有正确使用数据提供程序,结果在脚本的其他某些部分出现了错误。

假设您具有以下格式的excel数据:

| Username | Password |
| Ali      | Threee   |
| Puppy    | Two      |
| Dummy    | One      |

然后,您可以使用下面的代码使用多次登录的数据提供程序将用户名和密码发送到某些网站:

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.google.common.base.Function;

public class ReadXLDataToCards {
    private WebDriver driver;
    private ExcelUtility utility;
    private Wait<WebDriver> wait;

    @DataProvider
    public Object[][] getTestData() throws Exception {
        utility = new ExcelUtility();

        int totalRows = utility.getRowCount("Resources\\InputData.xlsx", "Sheet1");
        int totalColumns = utility.getColumnCount("Resources\\InputData.xlsx", "Sheet1");
        System.out.println("=> Total rows and columns is/are ("+totalRows+", "+totalColumns+")");

        Object[][] data = new Object[totalRows][totalColumns];
        for(int i=0;i<totalRows;i++) {
            for(int j=0;j<totalColumns;j++) {
                // Give your excel absolute path with the extension
                data[i][j] = new ExcelUtility().getData("Resources\\InputData.xlsx", "Sheet1", i, j);
            }
        }
        return data;
    }

    // No need to initialize the ChromeDriver again and again and no need to launch the site again and again so used 'firstTimeOnly'
    @BeforeMethod(firstTimeOnly = true)
    public void setup() {
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        driver = new ChromeDriver();

        driver.manage().window().maximize();
        driver.get("http://www.hackerrank.com/auth/login?h_l=body_middle_left_button&h_r=login");

        wait = new FluentWait<WebDriver>(driver).withTimeout(60, TimeUnit.SECONDS).pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
    }

    // Your test method goes here and this is just a sample working example
    @Test(dataProvider = "getTestData")
    public void test(String userName, String userPassword) {
        WebElement username = wait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.id("input-1"));
            }
        });

        WebElement userpass = wait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.id("input-2"));
            }
        });

        WebElement signIn = wait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.xpath("//span[contains(text(), 'Log In')]"));
            }
        });

        username.clear();
        username.sendKeys(userName);

        userpass.clear();
        userpass.sendKeys(userPassword);

        signIn.click();
    }
}

我没有分离这些类,而是将整个逻辑包含在同一类中。您可以根据需要更改此代码,这仅是示例工作示例。

下面是ExcelUtily类:

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtility {
    public String getData(String fileName, String sheetName, int rowNumber, int columnNumber) throws Exception {
        Workbook workbook = WorkbookFactory.create(new File(fileName));
        Sheet sheet = workbook.getSheet(sheetName);
        Row row = sheet.getRow(rowNumber);
        return row.getCell(columnNumber).getStringCellValue().trim();
    }

    public int getRowCount(String fileName, String sheetName) throws Exception {
        return WorkbookFactory.create(new File(fileName)).getSheet(sheetName).getLastRowNum() + 1;
    }

    public int getColumnCount(String fileName, String sheetName) throws Exception {
        return new XSSFWorkbook(new FileInputStream(fileName)).getSheet(sheetName).getRow(0).getLastCellNum();
    }
}

尝试创建一个excel工作表,并按照上述格式提供数据,然后运行脚本以查看执行情况,以便您对其工作原理有所了解...

希望对您有帮助...