使用WebDriver和selenium测试Swag Labs网站中,使用WebElement获取同一类名的元素值时,会多次获取第一个出现的值,导致无法获取多个不同值。

WebElement firstItemPrice = driver.findElement(By.className("inventory_item_price"));
        WebElement secondItemPrice = driver.findElement(By.className("inventory_item_price"));


        // 计算总价
        double totalPrice = Double.parseDouble(firstItemPrice.getText().substring(1)) +
                Double.parseDouble(secondItemPrice.getText().substring(1));
WebElement total = wait.until(ExpectedConditions.elementToBeClickable(By.className("summary_subtotal_label")));
        //WebElement total = driver.findElement(By.className("summary_total_label"));

        // 验证总价标签内容
        assertEquals(String.format("Item total: $%.2f",+ totalPrice), total.getText());

 

以上这段代码是通过类名“inventory_item_price”获取页面上的两个元素。findElement 方法(注意这里是单数 "Element")会返回匹配指定条件的第一个元素。这意味着,无论是 firstItemPrice 还是 secondItemPrice,你实际上都在获取相同的第一个元素。

为了获取具有相同类名的不同元素,需要使用 findElements(注意这里是复数 "Elements")方法,这将返回一个包含所有匹配元素的列表。

这样的代码获取到的值只能获取到第一个值也就是$29.9,导致最后计算出的预期值是29.9+29.9而并非实际上的$29.9+$9.9 

改进后的代码如下

List<WebElement> productPrices = driver.findElements(By.className("inventory_item_price"));

            // 获取第一个商品价格
            WebElement firstItemPrice = productPrices.get(0);

            // 获取第二个商品价格
            WebElement secondItemPrice = productPrices.get(1);
 // 计算总价
        double totalPrice = Double.parseDouble(firstItemPrice.getText().substring(1)) +
                Double.parseDouble(secondItemPrice.getText().substring(1));
WebElement total = wait.until(ExpectedConditions.elementToBeClickable(By.className("summary_subtotal_label")));
        //WebElement total = driver.findElement(By.className("summary_total_label"));

        // 验证总价标签内容
        assertEquals(String.format("Item total: $%.2f",+ totalPrice), total.getText());

设定中要获取两个不同的值,因此需要用findElemens将所有匹配元素获取后变成列表(列表索引从0开始)因此第一个元素就是第一个获取到的元素值$29.9,第二个元素就是第二个获取到的元素值$9.9。

测试通过:

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值