如何使用 Selenium 和 Java 单击产品列表中与产品相关的特定 'Add to cart' 按钮

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

这是我的测试 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");

            }
          }

        }

我正在尝试单击产品“Beans**”的 'Add to cart'。但是 selenium webdriver 单击对应于 'Brinjal' 的 'Add to cart' 按钮,这是下一个立即 product.Kindly 帮我解决这个问题。

要为 Beans 点击 ADD TO CARD,您需要使用 for the elementToBeClickable() and you can use either of the following :

  • 使用 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();
    
  • 浏览器快照:

下面的代码对我有用。您使用的 xpath ("//button[text() ='ADD TO CART']") 将不起作用,因为当您单击第一个项目("Cucumber")时,按钮文本已更改(从 'ADD TO CART' 到'✔ 添加')。在 for 循环中,在很短的时间内,更改的按钮文本保持不变,在下一个 for 循环中,添加的项目“Cucumber”被排除在外。所以在这里它会考虑预期项目旁边的项目(“Brinjal”被视为第 6 项而不是“Beans”)
所以你可以在这里使用 xpath "//div[@class='product-action']/button" 而不是 "//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();

    }
    }
    
    }

您需要添加“list = driver.findElements(By.cssSelector("h4.product-name"));"这一行再次进入 for 循环并更改添加到购物车按钮的 xpath

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

            }
          }