简体   繁体   中英

How to click a specific 'Add to cart' button with respect to a product from product list using Selenium and Java

This my testng class:

 public class EcommerceTest 
    {
     public static WebDriver driver;

          @Test

          public void addtoCartTest() throws InterruptedException
          {
              driver.get("https://rahulshettyacademy.com/seleniumPractise/");
              driver.manage().window().maximize();
              EkartPage1 oekart = new EkartPage1(driver);
              oekart.AddtoCart();

          }
          @BeforeTest
          public void beforeTest() {
              System.setProperty("webdriver.chrome.driver", "E:\\selenium\\chromedriver_win32\\chromedriver.exe");
              driver = new ChromeDriver();
              driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
          }

          @AfterTest
          public void afterTest() {
              //driver.close();
          }
    }

    /**/This my page object class**
    public class EkartPage1 
    {
        WebDriver driver;
        WebDriverWait wait;
        @FindBy(xpath = "//button[contains(text(),'ADDED')]")
        WebElement addedBtn;

        public EkartPage1(WebDriver driver)
        {
            wait = new WebDriverWait(driver, 30);
            PageFactory.initElements(driver, this);
            this.driver = driver;
        }
     **//This is my method to click Add to cart button**
        public void AddtoCart() throws InterruptedException /
        {
            String[] additems = {"Cucumber","Beans"};
          List<WebElement> list = driver.findElements(By.cssSelector("h4.product-name")); 

          for(int i=0;i<list.size();i++)
          {
              String[] productname = list.get(i).getText().split("-");
              String frmtdname = productname[0].trim();
              List itemsneeded = Arrays.asList(additems);

            if(itemsneeded.contains(frmtdname))
            {  

               List<WebElement> list2 =driver.findElements(By.xpath("//button[text() ='ADD TO CART']"));
               list2.get(i).click();
               System.out.println("One product added");

            }
          }

        }

I am trying to click on 'Add to cart' for the product 'Beans**.But the selenium webdriver clicks on 'Add to cart' button corresponding to 'Brinjal' which is the next immediate product.Kindly help me to resolve this issue.

To click on ADD TO CARD for Beans you need to use WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies :

  • Using xpath :

     driver.get("https://rahulshettyacademy.com/seleniumPractise/#/"); String item = "Beans"; new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//h4[@class='product-name' and starts-with(., '" +item+ "')]//following::div[2]/button[text()='ADD TO CART']"))).click();
  • Browser Snapshot:

豆子

The code below worked for me. The xpath ("//button[text() ='ADD TO CART']") you have used will not work as when you clicked on first item("Cucumber") the button text changed (from 'ADD TO CART' to '✔ ADDED'). Within for loop in very short time span the changed button text remain same and in next for loop the added item "Cucumber" excluded. So here it will consider the item next to expected item ("Brinjal" consider as 6th item instead of "Beans")
So you can use here xpath "//div[@class='product-action']/button" instead of "//button[text() ='ADD TO CART']".

    WebDriver Driver = new ChromeDriver();
    Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    Driver.manage().window().maximize();
    String url = "https://rahulshettyacademy.com/seleniumPractise/";
    Driver.get(url);
    String[] additems= {"Cucumber","Beans"};
    AddtoCart(Driver, additems);

    }

    public static void AddtoCart(WebDriver Driver, String[] additems) 
    {       
        
    List<WebElement> products=Driver.findElements(By.cssSelector("h4.product-name"));
    for(int i=0;i<products.size();i++)

    {
        
    String[] productname=products.get(i).getText().split("-");

    String frmtdname=productname[0].trim();

    //format it to get actual vegetable name

    //convert array into array list for easy search

    //  check whether name you extracted is present in arrayList or not-
    List itemsneeded = Arrays.asList(additems);

    if(itemsneeded.contains(frmtdname))

    {

    //click on Add to cart

    Driver.findElements(By.xpath("//div[@class='product-action']/button")).get(i).click();

    }
    }
    
    }

You need to add "list = driver.findElements(By.cssSelector("h4.product-name"));" this line again in for loop and also change the xpath of add to cart button

      public void AddtoCart() throws InterruptedException /
        {
          String[] additems = {"Cucumber","Beans"};
          List<WebElement> list = 
          driver.findElements(By.cssSelector("h4.product-name")); 

          for(int i=0;i<list.size();i++)
          {
         //added this line again
         list = driver.findElements(By.cssSelector("h4.product-name"));
      

              String[] productname = list.get(i).getText().split("-");
              String frmtdname = productname[0].trim();
              List itemsneeded = Arrays.asList(additems);

            if(itemsneeded.contains(frmtdname))
           {  //change the xpath of add to cart, take the class name

              List<WebElement> list2=driver.findElements(By.xpath("//div[@class='actions']/button"));
               list2.get(i).click();
               System.out.println("One product added");

            }
          }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM