当id和xpath是动态的时,如何识别并单击按钮

时间:2014-01-31 06:37:41

标签: selenium selenium-webdriver

在页面上,会显示多个产品,并且每个产品都有“添加到购物车”选项。

页面上显示的产品是动态的,xpath / ID不断变化。我想找到一个特定的产品,然后点击添加到购物车。如何查找产品并将其添加到购物车中?

以下是页面显示多个产品的一个示例: www1.macys.com/shop/product/hotel-collection-modern-lancet-bedding-collection?ID=1121719&CategoryID=7502

先谢谢

1 个答案:

答案 0 :(得分:2)

在每个产品的div中搜索您的产品,并从那里做您需要的。您可以使用以下代码:

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.
        }
    }
}