简体   繁体   中英

How to Click Random element from a list of elements returned by a search

I have page where list of products are displayed, I need to click only particular type of listings from the list so saved this particular type as "Webelement". Now, whenever I land on this page, I check a condition and click only on first product. But, my requirement is after checking a condition, I need to click any random product in the list. see my code below. kindly suggest.

 driver.findElement(By.linkText("ALL EQUIPMENT")).click();
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

     List <WebElement> listings = driver.findElements(By.cssSelector("a[href*='/listing?listingid']"));

              for (int i=0; i < listings.size(); i++) {

      WebElement requiredlisting = listings.get(i);
      System.out.println(i);
      requiredlisting.click();
     Thread.sleep(10000);


     getvalue = driver.findElement(By.xpath("//div[7]/span")).getText();
     System.out.println(getvalue);


         driver.findElement(By.xpath("//div[3]/div[2]/input")).click();
         Thread.sleep(10000);
         driver.findElement(By.id("listingQuestion")).click();
        Thread.sleep(10000);
         driver.findElement(By.id("listingQuestion")).sendKeys("Where is the listing located");
            Thread.sleep(10000);             
         driver.findElement(By.name("submitq")).click();
            Thread.sleep(10000);                         
         driver.findElement(By.xpath("//div/div[2]/div[3]/input")).click();
         Thread.sleep(10000);

         driver.findElement(By.id("uname")).click();
         driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
         driver.findElement(By.linkText("Sign Out")).click();

You can use the Random generator class.

   Random rand = new Random();
   string locator = string.Format("//div/div[2]/div[{0}]/input", rand.Next(5)); 
   // Where 5 is the number of the elements in the list
   driver.FindElement(By.Xpath(locator)).Click();

This is the code in C# it is almost 1 to 1 as in Java. Also, change the Xpath locator if this is not the correct locator of your list.

So, since your requirement is to click on any random element, then don't use for-loop for clicking on the element . You can use the Random class and initialize its object with the size of the list and click on any element on the list as below:

List <WebElement> listings = driver.findElements(By.cssSelector("a[href*='/listing?listingid']"));
Random r = new Random();
int randomValue = r.nextInt(listings.size()); //Getting a random value that is between 0 and (list's size)-1
listings.get(randomValue).click(); //Clicking on the random item in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM