使用Selenium WebDriver验证商品价格从高到低排序功能是否正常
商品价格排序校验解决方案
1. 主价格选择器获取
你测试的站点商品主价格的正确XPATH选择器如下,该选择器只会匹配每个商品卡片的主售价,自动排除划线旧价、税费标注内容://div[@class="product-thumb"]//p[@class="price"]
如果习惯用CSS选择器可以写div.product-thumb p.price,两者都可以直接使用。
2. 原有代码逻辑修正
你现有的代码存在两个核心问题:
- 直接对字符串格式的价格排序会出错,比如
$1,200和$800按字符串排序会得到$1,200 < $800的错误结果 - 默认的
Collections.sort()是升序排序,你需要校验的是价格从高到低的降序,逻辑完全相反
3. 修正后的完整可运行代码
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import static org.junit.Assert.assertEquals; public class PriceSortTest { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("http://tutorialsninja.com/demo/index.php?route=product/category&path=18&sort=p.price&order=DESC"); // 抓取所有主价格元素 List<WebElement> priceElements = driver.findElements(By.xpath("//div[@class=\"product-thumb\"]//p[@class=\"price\"]")); // 提取价格并转为数字格式,避免字符串排序错误 List<BigDecimal> prices = new ArrayList<>(); for (WebElement ele : priceElements) { // 处理文本:去掉$、逗号,截取到换行符之前的主价格部分,排除后面的税费内容 String priceText = ele.getText().split("\\n")[0] .replace("$", "") .replace(",", "") .trim(); prices.add(new BigDecimal(priceText)); } // 生成降序排序的对比列表 List<BigDecimal> sortedPrices = new ArrayList<>(prices); sortedPrices.sort(Comparator.reverseOrder()); // 校验当前页面价格是否符合降序规则 assertEquals(prices, sortedPrices); driver.quit(); } }
内容的提问来源于stack exchange,提问作者mikie
相关产品推荐
相关产品推荐

