问题
My html sample code is,
<div class="list">
<div class="dropdown">
<ul role="menu">
<li class="rsbListItem">one</li>
<li class="rsbListItem">two</li>
<li class="rsbListItem">three</li>
<li class="rsbListItem">four</li>
<li class="rsbListItem">five</li>
<li class="rsbListItem">six</li>
<li class="rsbListItem">seven</li>
<li class="rsbListItem">eight</li>
</ul>
</div>
</div>
How can i write Selenium scripts for this, and each time when i run it should select randomly.
I have tried to pick random elements,but it's selecting the same element each time. Here is my code.
List<WebElement> options = driver.findElements(By.xpath("//*[@role='menu']"));
Random rand = new Random();
int list= rand.nextInt(options.size());
options.get(list).click();
回答1:
Selenium is not my thing but
List<WebElement> options = driver.findElements(By.xpath("//*[@role='menu']"));
This will return a list of WebElement
match your request. So you should get the element (should be only one I guess) to work with it. You could also use findElement
I guess.
Then, you will need to get every Option
in the select you have.
List<WebElement> selects = driver.findElements(By.xpath("//*[@role='menu']"));
Random rand = new Random();
for(WebElement select : selects){
List<WebElement> options = // get every option in it
int list = rand.nextInt(options.size());
options.get(list).click();
}
回答2:
// Locate the dropdown menu
WebElement drpdown = driver.findElements(By.id("id of the dropdown menu"));
// click the dropdown menu
drpdown.click();
//Get the list of dropdown options
List<WebElement> itemsInDropdown = driver.findElements(By.id("id of the dropdown list"));
// Get the size of dropdown list
int size = itemsInDropdown.size();
// Generate the random number
int randomNumber = ThreadLocalRandom.current().nextInt(0, size);
// Clicking on random value
itemsInDropdown.get(randomNumber).click();
来源:https://stackoverflow.com/questions/44587164/select-randomly-from-dropdown-list