Here is the solution to find and click on the first Amazon best seller:
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(); // ensure chromedriver is downloaded
WebDriver driver = new ChromeDriver();
driver.get("https://www.amazon.com/s?k=socks+for+women&crid=O6H6S2VU5M66&sprefix=socks+%2Caps%2C74&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 the first best seller item
} else {
System.out.println("There are no best sellers found");
}
Thread.sleep(10 * 1000); // wait for 10 seconds before closing browser
driver.quit();
}
}
Console output:
Total amount of best sellers: 2