user3188928
user3188928

Reputation: 215

how to identify and click a button when id and xpath is dynamic

On a page, multiple products are displayed and 'add to cart' option is available for each product.

The products displayed on the page is dynamic and the xpaths/ids keep changing. I would like to find a specific product and click add to cart. how do I find and add the product to the cart?

following is one example where page shows multiple products: www1.macys.com/shop/product/hotel-collection-modern-lancet-bedding-collection?ID=1121719&CategoryID=7502

Thanks in Advance

Upvotes: 1

Views: 1344

Answers (1)

Husam
Husam

Reputation: 1105

Search each product's div for your product, and do what you need from there. You may use following code:

public void test(String product) {
    driver.get("http://www1.macys.com/shop/product/hotel-collection-modern-lancet-bedding-collection?ID=1121719&CategoryID=7502#bottomArea");
    product = "Hotel Collection Lancet 14\" x 26\" Decorative Pillow";

    List<WebElement> listProduct = driver.findElements(By.xpath("//*[contains(@id,'member') and contains(@class,'memberProducts')]")); //List which has all the product description and buttons.
//Iterate each element for the title with required product.
    for(WebElement eachElem:listProduct){
        String tmp = eachElem.findElement(By.xpath("//div[@class='memberUPCDetails']/img")).getAttribute("title"); //Get the title of nth element.
        if (tmp.equals(product)){ 
            WebElement button = eachElem.findElement(By.xpath("//img[@class='addToBagButton']")); 
            button.click(); //If title matches click on button for same element.
            break; //Break out of iteration.
        }
    }
}

Upvotes: 2

Related Questions