Wednesday, 8 February 2017

SELENIUM : HOW TO CLICK ON A LINK RANDOMLY:

SELENIUM : HOW TO CLICK ON A LINK RANDOMLY:



By using Random class from java.util package.
Steps:
1.Create Random class object
2.call a non static method called  nextInt(int number) method and pass integer value.Then it generate one random number between 0 to number-1.
(i.e  if we give number as 10 then it generate any value between 0-9,not 10)
syntax: public int nextInt(int bound)
Example:
package com.rameshsoft.rameshselenium;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class RandomClickDemo {
         
          @Test
          public void demo() throws InterruptedException
          {
                   System.setProperty("webdriver.gecko.driver", "C:\\Users\\ramesh\\Desktop\\java\\desk\\geckodriver-v0.11.1-win64\\geckodriver.exe");
                   WebDriver driver=new FirefoxDriver();
                   driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
                   driver.manage().deleteAllCookies();                  
                   driver.get("https://jqueryui.com");               
                   Thread.sleep(3000); 
List<WebElement> links= driver.findElements(By.xpath("//a"));
int count=links.size();
System.out.println("Number of links are:"+count); 
Random r=new Random();
int linkNo=r.nextInt(count);
WebElement link=links.get(linkNo);
System.out.println(link.getText());
Thread.sleep(2000);
link.click();
          }

}

No comments:

Post a Comment