Java+Selenium自动化:商品价格排序验证代码优化建议
Java + Selenium 价格排序验证代码优化方案
核心优化思路
- 用Java 8+ Stream API替代多层循环,实现链式数据转换,消除冗余的中间集合
- 整合元素提取、文本处理、类型转换为单一流式操作,简化代码结构
- 优化异常处理逻辑,适配Stream的函数式编程场景
优化后的完整代码示例
1. 从元素到BigDecimal列表的转换(合并步骤1+2)
直接通过Stream完成从WebElement到BigDecimal的链式转换,无需创建中间字符串集合:
import java.util.List; import java.util.stream.Collectors; import org.openqa.selenium.WebElement; import java.math.BigDecimal; List<BigDecimal> productPricesDecimalsAsc = baseMethods.findElements("ProductListing.ProductPrice") .stream() // 提取元素文本并去除前后空白 .map(webElement -> webElement.getText().trim()) // 转换为BigDecimal,处理原方法的检查异常 .map(str -> { try { return HelpersNL.cropAndParseToDecimal(str); } catch (ParseException e) { throw new RuntimeException("解析价格失败: " + str, e); } }) .collect(Collectors.toList());
2. 优化后的cropAndParseToDecimal方法
增加空值校验,并将检查异常转为运行时异常,适配Stream场景:
import java.math.BigDecimal; import java.text.NumberFormat; import java.text.ParseException; import java.text.DecimalFormat; import java.util.Locale; public class HelpersNL { public static BigDecimal cropAndParseToDecimal(final String productPriceAmount) { // 提前拦截无效输入 if (productPriceAmount == null || productPriceAmount.isBlank()) { throw new IllegalArgumentException("价格字符串不能为空或空白"); } // 裁剪价格字符串(保留中间有效数值部分) String decimalString = productPriceAmount.replaceAll("^..|.$", ""); final NumberFormat format = NumberFormat.getNumberInstance(Locale.GERMAN); if (format instanceof DecimalFormat) { ((DecimalFormat) format).setParseBigDecimal(true); } try { return (BigDecimal) format.parse(decimalString); } catch (ParseException e) { // 转换为运行时异常,避免在Stream中强制捕获 throw new RuntimeException("无法解析价格格式: " + decimalString, e); } } }
3. 排序验证(步骤3保留原逻辑,可扩展降序)
// 验证升序排列 Assert.assertTrue(Ordering.natural().isOrdered(productPricesDecimalsAsc)); // 如需验证降序,使用reverse() Assert.assertTrue(Ordering.natural().reverse().isOrdered(productPricesDecimalsAsc));
优化优势
- 消除了冗余的中间集合(原代码中的
productPricesStringsAsc),减少内存开销 - 代码逻辑连贯,从元素获取到类型转换一步完成,可读性更强
- 代码行数大幅减少,同时保持逻辑清晰
- 增加输入校验和异常封装,提升代码健壮性
内容的提问来源于stack exchange,提问作者Kermi
相关产品推荐
相关产品推荐

