Home > Mobile >  Find the locator for the first specially badged product in an eCommerce site using Selenium [JAVA]
Find the locator for the first specially badged product in an eCommerce site using Selenium [JAVA]

Time:06-23

I want to click on the First 'Best Seller' batched item of this site.

For example: I have searched for "Socks for women" on the website and I want to click on the first "Best Seller" Badged item in that page. This is the link: https://www.amazon.com/s?k=socks for women&crid=O6H6S2VU5M66&sprefix=socks ,aps,74&ref=nb_sb_ss_ts-doa-p_2_6

I have tried to get the item containers as List webElements and iterate through each element if there is any 'Best-seller' batch exist. I need to get the first found element to click on it. Unfortunately I am stuck with the logic. Any better solutions will be much appreciated.

List<WebElement> prd_con = driver.findElements(By.cssSelector("div[class*='s-card-container']"));
        for(WebElement prd : prd_con) {         

}

CodePudding user response:

Solution:

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

import java.util.List;

public class FindAndClickFirstAmazonBestSeller {

    @Test
    public void test() throws Exception {
        WebDriverManager.chromedriver().setup(); // download driver if not exist (for more details google 'how to use bonigarcia selenium')

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.amazon.com/s?k=socks for women&crid=O6H6S2VU5M66&sprefix=socks ,aps,74&ref=nb_sb_ss_ts-doa-p_2_6");

        List<WebElement> allBestSellers = driver.findElements(By.xpath("//span[text()='Best Seller']//ancestor::div[contains(@class,'s-card-container')]/div"));

        if (allBestSellers.size() > 0) {
            System.out.println("Total amount of best sellers: "   allBestSellers.size());

            allBestSellers.get(0).click(); // click on first item
        } else {
            System.out.println("There are no best sellers found");
        }
        
        Thread.sleep(10 * 1000); // sleep 10 secs, to prevent browser closing, can be removed
        driver.quit();
    }
}

Console output:

Total amount of best sellers: 2
  • Related