在selenium的下拉框中获取当前选定的选项

Loc*_*rde 2 c# selenium webdriver

我有一个与此类似的下拉列表:

<select id="PlaceOfBirth">
    <option value="">-- Please select --</option>
    <option value="1">Somewhere</option>    
    <option value="2">Somewhere else</option>    
    <option value="3">somewhere else again</option>
</select>
Run Code Online (Sandbox Code Playgroud)

现在在selenium中,我想确保在页面加载时-- Please select --默认选择它.

谷歌搜索,选择xpath和[selected ="selected"]看起来很有希望,但是,我不能使用它,因为我options没有选择属性开始.

所以我想,相反,我可以像这样选择第一个元素:

driver.FindElement(By.XPath("//select[@id='PlaceOfBirth']/*[1]"));
//the actual xpath being //select[@id='PlaceOfBirth']/*[1]
Run Code Online (Sandbox Code Playgroud)

虽然这确实很好地返回了第一个选项,但它不一定是选中的选项.如何确保当前选择的选项是我想要的 (value="", text="-- Please select --")

谢谢.

ps:我正在使用selenium webdriver
pps:我遇到过各种各样的答案,比如selectLocator等,但要么是php/java,要么我在命名空间中找不到它们......

And*_*ers 5

尝试:

var selectedItemText = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].options[arguments[0].selectedIndex].text;", element);
var selectedItemValue = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].options[arguments[0].selectedIndex].value;", element);
var selectedItemIndex = (long)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].selectedIndex;", element);
Run Code Online (Sandbox Code Playgroud)