1

I'm trying to making automation and I need to select random product in page.
That's my code and it's not working.

//Select random product.
    List<WebElement> allProducts= driver.findElements(By.xpath("//div[@class='m-grid-col-9']"));
    int allList= allProducts.size();
    Random random= new Random();
    int RandomUrun= random.nextInt(allList);
    allProducts.get(RandomUrun).click();

I'm trying to get random product in this website: https://www.turkcell.com.tr/pasaj/cep-telefonu

1 Answers1

0

You are using a wrong locator. //div[@class='m-grid-col-9'] is matching some container where all those products inside it. You can use this XPath instead:

"//div[@class='m-grid-col-4 product']"

The locator above can even be shortened to this CSS Selector:

"div.product"

So, instead of List<WebElement> allProducts= driver.findElements(By.xpath("//div[@class='m-grid-col-9']")); please try

List<WebElement> allProducts= driver.findElements(By.cssSelector("div.product"));

Also, you will need to scroll the randomly selected element into the view since not all the elements are initially inside the visible view port of the screen.

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • this time I tried as you said but this time it gave me the error "this element is not clickable". –  Nov 27 '22 at 21:50
  • 1
    Sure, after collecting all these elements you need to scroll to the element before clicking it since not all the products are initially inside the visible view port. I will add this to the answer – Prophet Nov 27 '22 at 21:53
  • Okay im waiting –  Nov 27 '22 at 21:53
  • Done. I hope you know how to scroll element into the view? – Prophet Nov 27 '22 at 21:55
  • I used js.executeScript("window.scrollBy(0,900)"); but gave same error again. –  Nov 27 '22 at 21:57
  • No, you need to scroll specific, the selected element into the view. For some elements you will not need to scroll at all, for others do, for others do it more. Depends on the location of randomly selected element – Prophet Nov 27 '22 at 21:59
  • Something like this: https://stackoverflow.com/a/20487332/3485434 – Prophet Nov 27 '22 at 22:04
  • In your case the element is already exists, so you will need to apply this `((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);` on it – Prophet Nov 27 '22 at 22:05
  • 1
    You'r the best! –  Nov 27 '22 at 22:10