Java Selenium LinkedIn登录测试 无法登出、Excel写入失败
问题说明
- 已创建名为
deneme5.xlsx的Excel文件,两列分别存储测试用的随机邮箱、密码数据 - 编写Java Selenium自动化脚本逐行读取账号组合,尝试登录LinkedIn
- 运行时出现两个异常:
- 正确账号登录成功后,无法执行退出操作
- 单条用例的测试通过/失败结果,无法写入目标Excel文件
- 运行异常截图:

原实现代码
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.time.Duration; import java.util.concurrent.TimeUnit; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class Excel_Read_Write { WebDriver driver; WebDriverWait wait; XSSFWorkbook workbook; XSSFSheet sheet; XSSFCell cell; public void ReadData() throws IOException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lenovo\\Desktop\\chromedriver.exe"); //location of cromdriver exe WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); driver.get("https://www.linkedin.com/login/tr"); driver.manage().window().maximize(); //new WebDriverWait(driver, Duration.ofSeconds(30)); File src= new File("C:\\Users\\Lenovo\\Desktop\\deneme5.xlsx"); //excel sheet which i put 10 random email and password which one of them is true FileInputStream finput = new FileInputStream(src); workbook = new XSSFWorkbook(finput); sheet= workbook.getSheetAt(0); for(int i=1; i<= sheet.getLastRowNum() ; i++) { XSSFCell cell3 =sheet.getRow(i).createCell(3); //this loop for writing all the email and passwords one by one System.out.print("Sena"); cell = sheet.getRow(i).getCell(0); cell .setCellType(CellType.STRING); driver.findElement(By.id("username")).sendKeys(cell.getStringCellValue()); cell = sheet.getRow(i).getCell(1); cell.setCellType(CellType.STRING); driver.findElement(By.id("password")).sendKeys(cell.getStringCellValue()); driver.findElement(By.className("btn__primary--large")).click(); driver.findElement(By.id("username")).clear(); String actualUrl="https://www.linkedin.com/feed/"; String expectedUrl= driver.getCurrentUrl(); if(actualUrl.equalsIgnoreCase(expectedUrl)) { //driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); cell3.setCellType(CellType.STRING); cell3.setCellValue("test passed"); driver.findElement(By.id("ember19")).click(); driver.findElement(By.linkText("Sign Out")).click(); } else { cell3.setCellValue("test failed"); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); driver.findElement(By.id("username")).clear(); }} FileOutputStream outputStream = new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\deneme5.xlsx"); workbook.write(outputStream); workbook.close(); }}
故障原因
登录后无法退出的原因
- 元素定位方式错误:代码中写死的
ember19是LinkedIn前端动态生成的ID,每次页面加载后ember开头的ID值都会变化,无法稳定定位到右上角个人菜单入口。 - 执行时序错误:点击登录按钮后没有等待页面跳转,立刻执行URL校验、查找登录页的
username输入框执行clear操作,登录成功跳转到Feed页后不存在该输入框,代码直接抛出元素找不到的异常,后续退出逻辑根本不会执行。 - 隐式等待配置滥用:隐式Wait是全局配置,只需要初始化driver时设置一次即可,循环内重复设置没有意义,也解决不了页面跳转的等待问题。
测试结果无法写入Excel的原因
- 文件流冲突:读取Excel的
FileInputStream没有关闭,就直接对同一个文件创建FileOutputStream写入,文件被输入流占用导致写入失败。 - 异常中断:前面的元素定位抛出异常后,程序直接终止,走不到最后写文件的代码段,修改的单元格内容自然无法落盘。
- 变量作用域错误:方法内重新定义了同名局部变量
WebDriver driver = new ChromeDriver(),覆盖了类全局的driver实例,后续如果扩展逻辑调用全局driver会触发空指针。
修复方案
- 移除方法内重复定义的局部driver,统一使用全局实例,初始化时配置一次隐式等待即可。
- 点击登录按钮后添加显式等待,等页面URL跳转到Feed页之后再做登录成功判断,不要立刻操作页面元素。
- 替换动态ID的定位逻辑,用稳定的CSS选择器定位右上角个人头像触发菜单,再点击退出选项。
- 调整clear操作的时机:输入账号密码前先清空输入框,避免上一轮测试残留内容;登录失败场景下等页面回到登录态再清空输入框准备下一轮测试。
- 所有文件流遵循先开后关原则,读取完Excel内容后立刻关闭输入流,再执行写入操作;添加try-catch块兜底,保证即使单条用例执行失败,也能走到最终的文件写入逻辑。
修复后可运行代码
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.time.Duration; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; 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; public class Excel_Read_Write { WebDriver driver; WebDriverWait wait; XSSFWorkbook workbook; XSSFSheet sheet; XSSFCell cell; public void ReadData() throws IOException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lenovo\\Desktop\\chromedriver.exe"); // 移除重复定义的局部driver,使用全局实例 driver = new ChromeDriver(); // 隐式等待全局只配置一次 driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15)); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.get("https://www.linkedin.com/login/tr"); driver.manage().window().maximize(); File src = new File("C:\\Users\\Lenovo\\Desktop\\deneme5.xlsx"); FileInputStream finput = new FileInputStream(src); workbook = new XSSFWorkbook(finput); sheet = workbook.getSheetAt(0); // 读取完成立刻关闭输入流,避免占用文件 finput.close(); for (int i = 1; i <= sheet.getLastRowNum(); i++) { XSSFCell resultCell = sheet.getRow(i).createCell(3); try { // 输入前先清空输入框,避免上一轮测试残留内容 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username"))).clear(); cell = sheet.getRow(i).getCell(0); cell.setCellType(CellType.STRING); driver.findElement(By.id("username")).sendKeys(cell.getStringCellValue()); driver.findElement(By.id("password")).clear(); cell = sheet.getRow(i).getCell(1); cell.setCellType(CellType.STRING); driver.findElement(By.id("password")).sendKeys(cell.getStringCellValue()); driver.findElement(By.className("btn__primary--large")).click(); // 显式等待页面跳转,最多等10秒 boolean loginSuccess = wait.until(ExpectedConditions.urlToBe("https://www.linkedin.com/feed/")); if (loginSuccess) { resultCell.setCellType(CellType.STRING); resultCell.setCellValue("test passed"); // 替换动态ID定位,用稳定的CSS选择器定位个人头像菜单 wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.global-nav__me span.global-nav__me-text"))).click(); wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Sign Out"))).click(); // 等退出完成回到登录页再进入下一轮 wait.until(ExpectedConditions.urlContains("login")); } else { resultCell.setCellValue("test failed"); } } catch (Exception e) { resultCell.setCellValue("test failed"); // 单条用例失败后回到登录页,避免影响下一轮测试 driver.get("https://www.linkedin.com/login/tr"); } } // 所有用例执行完再统一写入结果 FileOutputStream outputStream = new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\deneme5.xlsx"); workbook.write(outputStream); outputStream.close(); workbook.close(); driver.quit(); } }
注意:LinkedIn有反爬机制,频繁自动化登录可能会触发人机验证,导致脚本执行失败,测试时建议控制操作间隔。
内容的提问来源于stack exchange,提问作者Sena
相关产品推荐
相关产品推荐

