【问题标题】:Clicking on an element with the 5th highest price点击价格第 5 高的元素
【发布时间】:2022-11-16 02:12:06
【问题描述】:

拜托,我对自动化很陌生,一直在电子商务网站上练习。 我正在尝试根据价格以相反的顺序对项目进行排序,然后单击价格排名第 5 的项目。我卡住了

这是我的代码:

List<WebElement> price = driver.findElements(By.xpath("//span[@class='a-price-whole']"));

        // extract the prices from the price elements and store in a List
        List<Float> prices = new ArrayList<Float>();
        for (WebElement e : price)
        {
            prices.add(Float.parseFloat(e.getText()));
            
        }


        // sort the list
        
        Collections.sort(prices); 
        Collections.reverse(prices);

请协助

【问题讨论】:

    标签: java selenium-webdriver automated-tests


    【解决方案1】:

    我没有测试过这个,因为我没有必要的库,(所以可能会有轻微的错误)但我会像这样按价格获得前 5 个网络元素

    List<WebElement> price = driver.findElements(By.xpath("//span[@class='a-price-whole']"));
    List<WebElement> top5 = price.stream().sorted(new Comparator<WebElement>() {
            @Override
            public int compare(WebElement e1, WebElement e2) {
                return Float.parseFloat(e1.getText()) > Float.parseFloat(e2.getText());
            }
        }).limit(5).toList();
    

    然后你知道第 5 个元素是最昂贵的 5 个。另外,您可以访问网络元素而不仅仅是价格。并使用 click() selenium 方法单击它。

    您还可以添加您需要的任何保障措施,例如确保有 5 个要素,如果未列出价格怎么办等。但这至少应该足以让您开始

    【讨论】:

    • 非常感谢@M。罗杰斯,如果我想先对整个列表进行排序,然后选择第 5 个最高的。我是否删除限制,然后索引变量并单击它?
    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    相关资源
    最近更新 更多