RE: How to click on particular button?.

Hi,

How to click on particular button?, when the all identifiers are same?.

Please find the below Screenshot, HTML and application URL.

Image:

RE: How to click on particular button?.

HTML:


<input type="submit" class="wpsc_buy_button" name="Buy" value="Add To Cart">

URL:
http://store.demoqa.com/products-page/product-category/accessories/

Rocky Doctor Asked on September 7, 2014 in Selenium WebDriver.
Add Comment
6 Answers
Best answer

Hi Rocky,

You can use the Page object Model to handle it dynamically, please find the code below:


public class ProductListing_Page extends BaseClass {
private static WebElement element;
public ProductListing_Page(WebDriver driver){

super(driver);

}
public static class Product_1{
public static WebElement btn_AddToCart(){

element = null;

try{

element= driver.findElement(By.xpath(".//*[@id='default_products_page_container']/div[3]/div[2]/form/div[2]/div[1]/span/input"));

Log.info("Add to Cart button is found for Product 1");

}catch (Exception e){

Log.error("Product 1 Add to Cart button is not found");

throw(e);

}

return element;

}

}
public static class Product_2{
public static WebElement btn_AddToCart(){

element = null;

try{

element= driver.findElement(By.xpath(".//*[@id='default_products_page_container']/div[4]/div[2]/form/div[2]/div[1]/span/input"));

Log.info("Add to Cart button is found for Product 2");

}catch (Exception e){

Log.error("Product 2 Add to Cart button is not found");

throw(e);

}

return element;

}

}
}

Once you done with that, you can use the above code with the following code:


ProductListing_Page.Product_1.btn_AddToCart.click();

And if there are many items you are intrested in during your test, then it would be great if you just create one method for ‘Add to Cart’  and pass the [div] number as an argument to the method.


public class ProductListing_Page extends BaseClass {
private static WebElement element;
public ProductListing_Page(WebDriver driver){

super(driver);

}
public static class Product{
public static WebElement btn_AddToCart(int Index){

element = null;

int iIndex = Index;

try{

element= driver.findElement(By.xpath(".//*[@id='default_products_page_container']/div["+iIndex+"]/div[2]/form/div[2]/div[1]/span/input"));

Log.info("Add to Cart button is found for Product");

}catch (Exception e){

Log.error("Product Add to Cart button is not found");

throw(e);

}

return element;

}

}
}

Above code can be used like this:


ProductListing_Page.Product_2.btn_AddToCart(3).click();

Best Regards,
Lakshay Sharma

Professor Answered on September 9, 2014.

Ufff.. Now I do not have any road blocks. Accepted.

on September 9, 2014.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.