Home > front end >  I can't do selenium java random click
I can't do selenium java random click

Time:01-25

enter image description here

I want to do a rondom click with selenium, but I can't. I searched but couldn't find it. I want to choose the sizes in the photo randomly. Because the sizes may be out of stock and my test will fail.

I ask for your support. I tried with list methods and I didn't.

CodePudding user response:

As you have not shared the HTML structure, can't suggest you on the actual code, however see the algorithm below:

Solution1: Assuming the dropdown has select tag:

  1. Get the dropdown values into a Select object, call it dropdownValues

    Select dropdownValues= new Select(driver.findElement(By.name("name of the element")));
    
  2. Create an instance(object) of Random class and generate a random number in the dropdown index range

  3. Select the random index from the dropdownValues

    dropdownValues.selectByIndex(randomElement);
    

Solution2: Assuming the dropdown does not have select tag:

  1. Get the dropdown values into a List, example below

    List<WebElement> dropdownValues = driver.findElements(By.xpath("enter xpath here"));
    
  2. Create an instance(object) of Random class like below

    Random rand = new Random();
    
  3. Select the random index from the List dropdownValues

    dropdownValues.get(rand.nextInt(dropdownValues .size()));
    

CodePudding user response:

2 approach for this. 1.

WebElement InputBox = driver.findElement(by.xpath("xpath of input box"));`
     InputBox.click();
        WebElement DropDownAttribute = driver.findElement(by.xpath("//*[text()='Xs']"));
        DropDownAttribute.click();

2.With Loop

 List<WebElement> list = driver.findElements(by.xapth("Xpath of all the dropdown entity"));
for(WebElement ele:list){
if(ele.getText().equals("Xs")){
ele.click();
}
}

CodePudding user response:

WebElement Size = driver.findElement(By.id("size-select"));

Select slc2 = new Select(Size);
slc2.selectByVisibleText("Xs");

This way, xs is selected, but if there is no xs size, it gives an error. I want you to choose whichever from the list there.

  • Related