简体   繁体   中英

How do I select a button randomly with WebDriver?

I am testing price comparisons web application and I would like to randomly select one of the "Apply Now" buttons. I had tried: (and other similar scenario example from stack)

But every time it select 1st Apply now button. I would like to select different button every time. HTML:

<div class="applyNowButtonContainer">
<a class="join-now" data-productid="******" data-excessid="******" data-href="/XXXXX/ApplyNow_prepare.action?rank=1&hash=onclick="Within.joinNow(this);" href="javascript:void(0)">Apply Now</a>
</div>

Here you go:

// get all links by xpath
List<WebElement> links = driver.findElements(By.xpath("//*[contains(text(), 'Apply Now')]));

// select a random one
Random gen = new Random();
WebElement link = links.get(gen.nextInt(list.size()));

link.click();

Query all buttons by type or class and use random index on the array of buttons

Here is how you can get random index within the range: Generating unique random numbers (integers) between 0 and 'x'

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