Java爬虫代码无法对亚马逊印度站价格排序及获取最值,报NumberFormatException
问题解决:亚马逊印度站爬虫价格排序的NumberFormatException异常
问题根源
你遇到的NumberFormatException: empty String,是因为通过CSS选择器获取的元素中,有部分元素的文本在去掉₹和逗号后变成了空字符串,调用Double.parseDouble时自然报错。另外代码还存在泛型缺失的问题,原始List会导致类型不安全。
解决方案
1. 精准过滤有效价格
在将处理后的字符串添加到列表前,先做非空校验和数字有效性校验,过滤掉无效数据。
2. 优化CSS选择器
原选择器span[class='a-size-base a-color-price']可能会选中非商品价格的元素,改用更精准的选择器定位商品价格(结合商品容器上下文缩小范围)。
3. 使用泛型保证类型安全
将List改为List<Double>,避免后续排序时的类型转换问题。
4. 直接获取最值
排序后的列表,第一个元素是最低价,最后一个是最高价,无需额外计算。
修正后的完整代码
driver.get("https://www.amazon.in/gp/bestsellers/?ref_=nav_cs_bestsellers"); List<Double> priceList = new ArrayList<>(); // 更精准的选择器:定位商品容器内的价格元素 List<WebElement> priceElements = driver.findElements(By.cssSelector(".zg-grid-general-faceout .a-size-base.a-color-price")); for (WebElement element : priceElements) { String priceText = element.getText().trim(); // 先过滤空文本 if (priceText.isEmpty()) { continue; } // 移除₹和逗号,处理成纯数字字符串 String cleanPrice = priceText.replaceAll("[₹,]", "").trim(); // 再次校验,确保处理后不是空串且能转成Double try { double price = Double.parseDouble(cleanPrice); priceList.add(price); } catch (NumberFormatException e) { // 跳过无效的价格格式 System.out.println("跳过无效价格:" + priceText); continue; } } // 排序(从低到高) Collections.sort(priceList); System.out.println("价格排序结果:" + priceList); // 获取最值 if (!priceList.isEmpty()) { double lowestPrice = priceList.get(0); double highestPrice = priceList.get(priceList.size() - 1); System.out.println("最低价:₹" + lowestPrice); System.out.println("最高价:₹" + highestPrice); } else { System.out.println("未获取到有效价格数据"); }
关键改动说明
- 用
List<Double>替代原始List,保证类型安全,避免排序时的隐式类型转换问题。 - 新增双重校验:先检查原始文本是否为空,处理后再次校验并通过
try-catch捕获无效格式,确保只有有效数字进入列表。 - 优化CSS选择器,通过
.zg-grid-general-faceout(商品容器类)缩小范围,减少非价格元素的干扰。 - 新增最值获取逻辑,直接从排序后的列表首尾取值。
内容的提问来源于stack exchange,提问作者Darshan Kadam
相关产品推荐
相关产品推荐

