如何修改Selenium代码以获取所有含重复价格的商品品牌-价格对?
你的问题出在HashMap的键唯一性上——当多个商品价格相同时,新存入的品牌名会覆盖掉之前的,所以最终每个价格只保留了最后一个商品的品牌名。
修改方案
核心思路是把Map的value从单个字符串改成字符串列表,让同一个价格可以对应多个品牌名。
1. 调整数据结构
把原来的HashMap<Integer, String>替换成HashMap<Integer, List<String>>,这样每个价格键对应一个品牌名集合。
2. 修改循环逻辑
遍历商品时,针对每个价格做判断:
- 如果价格已在Map中,就把当前品牌名追加到对应列表里
- 如果价格不在Map中,就新建一个列表,加入当前品牌名后再存入Map
3. 调整输出与排序逻辑
输出时要遍历每个价格对应的所有品牌名,排序部分可以保留原来的逻辑,但输出要适配新的数据结构。
修改后的完整代码
List<WebElement> list_of_products = driver.findElements(By.xpath(loc.getProperty("brandName"))); List<WebElement> list_of_products_price = driver.findElements(By.xpath(loc.getProperty("finalPrice"))); String product_name; String product_price; int int_product_price; // 变更数据结构:每个价格对应一个品牌名列表 HashMap<Integer, List<String>> map_final_products = new HashMap<>(); for (int i = 0; i < list_of_products.size(); i++) { product_name = list_of_products.get(i).getText(); product_price = list_of_products_price.get(i).getText(); product_price = product_price.replaceAll("[^0-9]", ""); int_product_price = Integer.parseInt(product_price); // 处理同价格商品的存储逻辑 if (map_final_products.containsKey(int_product_price)) { // 价格已存在,追加品牌名到对应列表 map_final_products.get(int_product_price).add(product_name); } else { // 价格不存在,新建列表并添加当前品牌名 List<String> brandList = new ArrayList<>(); brandList.add(product_name); map_final_products.put(int_product_price, brandList); } } // 输出所有商品对(适配新数据结构) Reporter.log("All the prices and products we found:\n", true); for (Map.Entry<Integer, List<String>> entry : map_final_products.entrySet()) { Reporter.log("价格: " + entry.getKey() + ",对应品牌: " + entry.getValue().toString() + "\n", true); } // 保留价格排序逻辑,可按排序后输出 Set<Integer> allkeys = map_final_products.keySet(); ArrayList<Integer> array_list_values_product_prices = new ArrayList<>(allkeys); Collections.sort(array_list_values_product_prices); // 按价格升序输出(可选) Reporter.log("\n按价格升序排列的商品:\n", true); for (int price : array_list_values_product_prices) { Reporter.log("价格: " + price + ",对应品牌: " + map_final_products.get(price).toString() + "\n", true); }
关键改动说明
- 数据结构变更:
HashMap<Integer, List<String>>确保同价格的品牌名不会被覆盖,每个价格可以关联多个品牌 - 循环判断逻辑:通过
containsKey检查价格是否已存在,分别执行追加或新建列表的操作 - 输出逻辑优化:遍历Map的键值对,每个价格对应输出所有关联的品牌名,完整保留所有商品数据
内容的提问来源于stack exchange,提问作者Péter Sánta
相关产品推荐
相关产品推荐

