Search code examples
xpathselenium-webdriverproduct

Selenium webdriver- how to select a product when all products have same class (amazon.in)


I am trying to automate amazone.in. I want to click on a particular product. But in Amazon.in, all products have same class.

Product 1

<h2 class="a-size-medium s-inline s-access-title a-text-normal">Puma Men's Storm Ind Mesh Running Shoes</h2>

Product 2

<h2 class="a-size-medium s-inline s-access-title a-text-normal">Nike Men's Eliminate Ii Mesh Running Shoes</h2>

How can i proceed?

Below is my code

 driver.manage().window().maximize();
       driver.get("http://amazon.in");
       driver.findElement(By.id("twotabsearchtextbox")).sendKeys("shoes");
       driver.findElement(By.id("twotabsearchtextbox")).submit();
       driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
       driver.findElement(By.xpath("//h2[@class='a-size-medium s-inline s-access-title a-text-normal']")).click();

Is it possible to click on an element using 'title' tag?


Solution

  • You can resolve this by adding name of the product into the xpath, to narrow it down.

    driver.findElement(By.xpath("//h2[@class='a-size-medium s-inline s-access-title a-text-normal' and contains(text(), \"Nike Men's Eliminate Ii Mesh Running Shoes\")]")).click();
    

    The above code will click on the first product. You can just replace the names of product and use it to click on the concerned one.