如何使用 Selenium 从 HTML5 数据列表中 select

How to select from a HTML5 datalist with Selenium

我正在尝试 select 来自数据列表,但似乎只有列表中的第一个元素 select 可用。

这是一个 HTML 片段:

<td>
<input id="applianceFilterTextbox" class="flat" name="applianceFilter" list="applianceNames" value="ROC-1006 - B827EBB5D539" style="width: 100%"/>
<datalist id="applianceNames">
<!-- ngRepeat: app in appliances -->
<option class="ng-binding ng-scope" ng-repeat="app in appliances" value="ROC-1006 - B827EBB5D539" ng-value="app.DisplayName">ROC-1006 - B827EBB5D539</option>
<!-- end ngRepeat: app in appliances -->
<option class="ng-binding ng-scope" ng-repeat="app in appliances" value="ROC-1007 - B827EBD15125" ng-value="app.DisplayName">ROC-1007 - B827EBD15125</option>
<!-- end ngRepeat: app in appliances -->
<option class="ng-binding ng-scope" ng-repeat="app in appliances" value="ROC-1008 - B827EB05DEF3" ng-value="app.DisplayName">ROC-1008 - B827EB05DEF3</option>
<!-- end ngRepeat: app in appliances -->
<option class="ng-binding ng-scope" ng-repeat="app in appliances" value="ROC-1009 - B827EB2A379C" ng-value="app.DisplayName">ROC-1009 - B827EB2A379C</option>
<!-- end ngRepeat: app in appliances -->
</datalist>
</td>

我的模块如下:

public void SelectApplianceFromDatalist(int index)
{
    ExplicitWait.waitElementToBeClickable(driver, 25, appliancesFilterTextBox);
    appliancesFilterTextBox.Clear();
    appliancesFilterTextBox.Click();
    string select1 = driver.FindElement(By.XPath("//*[@id='applianceNames']/option['" + index + "']")).GetAttribute("value");
    index++;
    string select2 = driver.FindElement(By.XPath("//*[@id='applianceNames']/option['" + index + "']")).GetAttribute("value");
    index++;
    string select3 = driver.FindElement(By.XPath("//*[@id='applianceNames']/option['" + index + "']")).GetAttribute("value");
    index++;
    string select4 = driver.FindElement(By.XPath("//*[@id='applianceNames']/option['" + index + "']")).GetAttribute("value");

    appliancesFilterTextBox.SendKeys(driver.FindElement(By.XPath("//*[@id='applianceNames']/option['"+ index +"']")).GetAttribute("value"));
}

select1、select2、select3 和 select4 仅用于调试目的。当使用索引值例如 3 调用模块时,它们都包含第一个选项的值。

尝试使用简单方法 sendKeys() 发送您需要的值,例如 -

    driver.findElement(By.id("applianceFilterTextbox")).clear();
    driver.findElement(By.id("applianceFilterTextbox")).sendKeys("ROC-1008 - B827EB05DEF3");

它将清除默认选择值并输入您需要的值。

另一件事是我认为你使用的方法是正确的,但你的 XPath 中有一个小错误。改变

By.XPath("//*[@id='applianceNames']/option['" + index + "']") 

By.XPath("//*[@id='applianceNames']/option["+ index +"]")