Связать / объединить 2 разных xpath Java Selenium - PullRequest
0 голосов
/ 01 июня 2019

Этот URL будет отображать результаты поиска продукта на сайте Amazon.
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']

Есть ли способ объединить эти 2, чтобы я мог связать название продукта с ценой. 1 Я могу думать так:

// 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']
}

Если у вас есть идея для более простого решения, пожалуйста, предложите. Заранее спасибо.

1 Ответ

0 голосов
/ 02 июня 2019

Я бы предпочел получить все элементы, а затем перебрать каждый из них в цикле, как показано ниже.

    // 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...