1

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.

Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
vijesh
  • 23
  • 1
  • 4
  • you have to pass specific identifiers ( like id )when select the elements , your code seems like it will load all the buttons in the page which has text as ADD TO CARD , and based on value i the corresponding button element from list is clicked. – saravana Jun 17 '20 at 06:28
  • list2.get(i).click(); have you checked what list2.get(i) returns? – Stultuske Jun 17 '20 at 06:53
  • @saravana Thank you for the info. Please find the html code below: Unable to see any id.
    Beans - 1 Kg

    Beans - 1 Kg

    82

    – vijesh Jun 17 '20 at 07:49
  • @Stultuske Thank you for your response. i am getting the following for list2.get(i): : get(i)=[[ChromeDriver: chrome on WINDOWS (390554e046a50efbb061d84fb010b107)] -> xpath: //button[text() ='ADD TO CART']] – vijesh Jun 17 '20 at 08:08

3 Answers3

0

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:

Beans

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • I have a small query.When we use "starts-with(., '" +item+ "')" ,does dot(.) indicates only text starting with 'item'?Or will it refer to any class,id or any attribute names starting with 'item'?Thanks in advance – vijesh Jun 17 '20 at 09:46
  • @vijesh The dot(.) refers to the text or innerHTML. – undetected Selenium Jun 17 '20 at 10:17
0

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();

    }
    }
    
    }
arpita biswas
  • 144
  • 1
  • 6
0

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");

            }
          }