You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Selenium WebDriver与POI实现Excel多凭证登录测试,求精简代码

Simple Selenium + POI Login Test Using .xls Credentials

Hey there! Let's put together a straightforward, minimal-class solution for your login testing scenario using Selenium WebDriver and Apache POI to read those .xls credential files. Since you already have the POI jars imported, we can jump right into the code.

Quick Prerequisite Check

Just double-check you have the right POI jar for .xls support (poi.jar — that's the one for older Excel formats). And make sure your Selenium WebDriver (ChromeDriver, FirefoxDriver, etc.) is set up correctly.

Implementation (Only 2 Classes)

First, a lightweight utility class to handle reading credentials from your .xls file. It's simple and focused only on getting the data we need:

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExcelCredentialReader {
    // Returns a list of [username, password] pairs from the first sheet of the .xls file
    public static List<String[]> getCredentials(String excelFilePath) throws IOException {
        List<String[]> credentialList = new ArrayList<>();
        
        FileInputStream fileStream = new FileInputStream(excelFilePath);
        HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
        HSSFSheet sheet = workbook.getSheetAt(0); // Use the first sheet for credentials

        // Skip the header row (assuming your Excel has headers like "Username" / "Password")
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            String username = sheet.getRow(rowNum).getCell(0).getStringCellValue();
            String password = sheet.getRow(rowNum).getCell(1).getStringCellValue();
            credentialList.add(new String[]{username, password});
        }

        // Clean up resources
        workbook.close();
        fileStream.close();
        return credentialList;
    }
}

Next, the main test class that ties together Selenium and the credential reader. This is where the login testing happens:

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

public class LoginPageTest {
    public static void main(String[] args) {
        // Set path to your WebDriver executable (update this to match your setup)
        System.setProperty("webdriver.chrome.driver", "path/to/your/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        try {
            // Load credentials from your .xls file
            List<String[]> credentials = ExcelCredentialReader.getCredentials("path/to/your/credentials.xls");

            // Loop through each credential pair to test login
            for (String[] cred : credentials) {
                driver.get("https://your-login-page-url.com"); // Replace with actual login URL

                // Enter credentials (update locators to match your login page's elements)
                driver.findElement(By.id("username")).sendKeys(cred[0]);
                driver.findElement(By.id("password")).sendKeys(cred[1]);
                driver.findElement(By.id("login-submit")).click();

                // Basic login success/failure check (adjust this to your app's behavior)
                if (driver.getCurrentUrl().contains("dashboard")) {
                    System.out.println("✅ Login successful for: " + cred[0]);
                } else {
                    System.out.println("❌ Login failed for: " + cred[0]);
                }

                // Navigate back to login page for next test (or add logout logic if needed)
                driver.navigate().back();
            }
        } catch (IOException e) {
            System.err.println("Error reading Excel file: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Make sure we close the driver no matter what
            driver.quit();
        }
    }
}

Key Notes to Adjust for Your Setup

  • Element Locators: Replace By.id("username"), By.id("password"), and By.id("login-submit") with the actual locators (XPath, CSS selector, name, etc.) from your login page. Use browser dev tools to find these!
  • Excel Structure: Your .xls file should have a header row (first row) with labels like "Username" and "Password", then each row below has a test credential pair.
  • WebDriver Choice: If you're using Firefox or Edge, swap out ChromeDriver with FirefoxDriver or EdgeDriver, and update the system property path accordingly.
  • Validation Logic: The current success check looks for "dashboard" in the URL — tweak this to match how your app indicates a successful login (e.g., a welcome message, specific element presence).

内容的提问来源于stack exchange,提问作者Shikha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:04:45