【问题标题】:Relate/combine 2 different xpath Java Selenium关联/组合 2 个不同的 xpath Java Selenium
【发布时间】:2019-10-17 23:31:32
【问题描述】:

此网址将显示产品在亚马逊网站中的搜索结果。
https://www.amazon.com/s?k=yellow+puma+shoes&s=price-asc-rank&qid=1559364287&ref=sr_st_price-asc-rank

使用这个 xpath 我可以获得产品名称

//span[@class='a-size-base-plus a-color-base a-text-normal']

使用这个 xpath 我可以得到价格

//span[@class='a-offscreen']

有没有办法将这两者结合起来,以便我可以将产品名称与价格联系起来。我能想到的一种方法是:

//span[@class='a-size-base-plus a-color-base a-text-normal']

List<WebElements> allProductNames**** Save them in a list. Then run a for loop

for()
{
text = getText
//span[text()='PUMA Mens Basket Classic']/../../../../../..//span[@class='a-offscreen']
}

如果您有更简单的解决方案的想法,请提出建议。提前致谢。

【问题讨论】:

    标签: selenium xpath


    【解决方案1】:

    我宁愿获取所有项目,然后在循环中遍历每个项目,如下所示。

        // get all products
        List<WebElement> products = driver.findElements(By.xpath("//span[@data-component-type='s-search-results']//div[@class='sg-row'][2]"));
        // create a map (consider it as dictionary that  to hold key value pair) to hold product and price
        Map<String, String> map = new HashMap<String, String>();
        for (WebElement product : products) {
            String item = "";
            String price = "";
            // get product name
            item = product.findElement(By.xpath(".//span[@class='a-size-base-plus a-color-base a-text-normal']")).getText();
            // get product price (some products have range so we have to get the prices and display)
            List<WebElement> prices = product.findElements(By.xpath(".//span[@class='a-offscreen']"));
            for (WebElement pPrice : prices) {
                if (price !=""){
                    price = price + "-" + pPrice.getAttribute("textContent");
                }else {
                    price = pPrice.getAttribute("textContent");
                }
            }
            // push the product and price to the map
            map.put(item, price);
    
        }
        System.out.println(map);
    

    【讨论】:

    • 如果我理解正确,这就是您所做的:1) 在产品列表中您保存了所有信息(价格、名称、评论等) 2) 在 HashMap 中添加项目和价格。为什么该项目不是列表,但价格是。我认为该项目也必须是一个列表。谢谢。
    • 我明白了,因为如果它是一个列表,那么您将无法使用 getText() 保存为字符串。
    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2012-08-30
    • 2013-10-14
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多