我需要通过名称从列表中选择一个项目。我尝试使用“选择”,但收到“元素当前不可见,因此可能无法与之交互”的错误。以下是我使用Select:
的脚本driver.findElement(By.xpath(".//*[@id='miscinfo_div']/ol/li[1]/div/fieldset/div/div[2]/div/div/ul/li"));
Select select = new Select(driver.findElement(By.id("companionPositionSelect")));
select.selectByVisibleText("Bottom1-Top1");
我也尝试过List。它按索引选择项目,但我只需要通过文本选择项目。我猜List没有选择按文本选择项目的选项。这是我的List脚本:
List<WebElement> availableCompPositions = driver
.findElements(By
.xpath("//input[@id='companionPositionSelect_a_search']//following::div[1]/ul/li"));
// select Bottom1-Top1 and add in the SELECTED menu
availableCompPositions.get(4).click();
还附加了页面的HTML。
HTML:
<div style="" id="miscinfo_div" class="toggler">
<ol>
<li>
<span>17.</span>
<label class="shufflelabel">
<div id="companionPositions_label">
<b> Companion Positions </b>
</div>
</label>
<div>
<fieldset class="shuttle_fieldset">
<legend></legend>
<div class="shuffle-box">
<select multiple="" id="companionPositionSelect" class="select2side" name="companionPositionSelect" style="display: none;">
<option value="20408" title="Bottom-BottomLeft-BottomRight">Bottom-BottomLeft-BottomRight</option>
<option value="20391" title="Bottom-Middle-Top">Bottom-Middle-Top</option>
<option value="20382" title="Bottom-Top" selected="selected">Bottom-Top</option>
<option value="20392" title="Bottom1-Middle1-Top1" selected="selected">Bottom1-Middle1-Top1</option>
<option value="20383" title="Bottom1-Top1">Bottom1-Top1</option>
<option value="20393" title="Bottom2-Middle2-Top2">Bottom2-Middle2-Top2</option>
</select>
</div>
答案 0 :(得分:3)
查看错误,我假设您正在尝试过早执行某项操作。以下程序应明确等待最多10秒才能找到元素
添加explicit
等待,直到元素存在
//explicit wait
By byCss = By.cssSelector("#companionPositionSelect>option[value='20383']");
WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(byCss));
element.click();