我无法从下面有html代码的下拉列表中选择随机值。
<div class='ui-dropdown-items-wrapper'>
<ul class='ui-dropdown-items ui-dropdown-list' role='listbox'>
<cdk-virtual-scroll-viewport class='cdk-virtual-scroll-viewport'>
<div class='cdk-virtual-scroll-content-wrapper'>
<p-dropdownitem class='ng-tns-c14'>
<li role='option' class='ui-dropdown-items ui' area-label="apple">
<span class='ng-star-inserted'>apple</span>
</li>
</p-dropdownitem>
<p-dropdownitem class='ng-tns-c14'>
<li role='option' class='ui-dropdown-items ui' area-label="Banana">
<span class='ng-star-inserted'>Banana</span>
</li>
</p-dropdownitem>
<p-dropdownitem class='ng-tns-c14'>
<li role='option' class='ui-dropdown-items ui' area-label="Mango">
<span class='ng-star-inserted'>Mango</span>
</li>
</p-dropdownitem>
</div>
<div class="cdk-virtual-scroll-spacer"></div>
</cdk-virtual-scroll-viewport>
</ul>
</div>
我尝试过下面的代码,但没有成功。。请任何人帮我从上面的HTML代码中选择随机值。
List<WebElement> options = driver.findElements(By.xpath("//*[@role='option']"));
Random rand = new Random();
int list= rand.nextInt(options.size());
options.get(list).click();
你能试试这个XPath吗?
List<WebElement> options = driver.findElements(By.xpath("//p-dropdownitem/li[@role='option']/span"));
int size = options.size();
options.get(new Random().nextInt(size)).click();
我修改了XPath,它运行良好,但在执行下拉选择之前,我需要单击下拉列表,然后只加载li/span列表。
将XPath修改为:
//label[@for='year']/../div//li[not(contains(.,'--select--'))]
最终代码:
List<WebElement> options = driver.findElements(By.xpath("//label[@for='year']/../div//li[not(contains(.,'--select--'))]"));
Random rand = new Random();
int list= rand.nextInt(options.size());
options.get(list).click();