使用javascript在selenium网络驱动程序中选择下拉列表项



我一直在努力使用javascript在selenium webdriver中选择下拉列表项。我的任务是打开https://pastebin.com/然后使用selenium webdriver javascript从下拉列表中选择"10 Minutes"。我已经实现了用以下方法打开下拉列表:

await driver.findElement(By.id(`postform-expiration`)).click()

尝试选择下拉列表项li值和id:

await dropdown.findElement(By.css(`li[value="10 Minutes"]`)).click()
// and
await driver.findElement(By.css(`//*[@id="select2-postform-expiration-result-b5nq-10M"]`)).click()

但他们都无法选择下拉列表项。

下拉列表的结构如下:

<div class="col-sm-9 field-wrapper">
<select id="postform-expiration" class="form-control select2-hidden-accessible" name="PostForm[expiration]" data-s2-options="s2options_7ebc6538" data-krajee-select2="select2_a09a7382" style="width: 1px; height: 1px; visibility: hidden;" data-select2-id="postform-expiration" tabindex="-1" aria-hidden="true">
<option value="N" data-select2-id="4">Never</option>
<option value="B" data-select2-id="11">Burn after read</option>
<option value="10M" data-select2-id="12">10 Minutes</option>
<option value="1H" data-select2-id="13">1 Hour</option>
<option value="1D" data-select2-id="14">1 Day</option>
<option value="1W" data-select2-id="15">1 Week</option>
<option value="2W" data-select2-id="16">2 Weeks</option>
<option value="1M" data-select2-id="17">1 Month</option>
<option value="6M" data-select2-id="18">6 Months</option>
<option value="1Y" data-select2-id="19">1 Year</option>
</select><span class="select2 select2-container select2-container--default select2-container--open select2-container--above select2-container--focus" dir="ltr" data-select2-id="3" style="width: 100%;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="true" tabindex="0" aria-disabled="false" aria-labelledby="select2-postform-expiration-container" aria-owns="select2-postform-expiration-results" aria-activedescendant="select2-postform-expiration-result-e4wf-1D"><span class="select2-selection__rendered" id="select2-postform-expiration-container" role="textbox" aria-readonly="true" title="Never">Never</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>
</div>

我感谢你的帮助。提前感谢!

为什么不试试select方法呢。它应该与特定的下拉列表一起工作。如下所示:

Select selectTime = new Select(driver.findElement(By.className("select2-selection select2-selection--single")));
selectTime.selectByValue("10 Minutes");

此外,如果这不起作用,那么试试这样的方法(这与你的方法更相似(:

await dropdown.findElement(By.id(`select2-postform-expiration-container`)).click()
await driver.findElement(By.xpath(`//*[text("10 Minutes"))).click();

最新更新