Java 从Selenium中的下拉列表中以文本/字符串形式获取所选选项?

Java 从Selenium中的下拉列表中以文本/字符串形式获取所选选项?,java,xpath,selenium-webdriver,Java,Xpath,Selenium Webdriver,我有一种情况,需要从下拉列表中以文本或字符串的形式获取当前选择,并对其进行比较以获得进一步的断言,但是当我尝试getText()时,我会在下拉列表中获得完整的项目列表,如何从下拉列表中获取当前选择的项目 <form id="MODIFY_ATTRIBUTES" class="formList" method="post" action="jfn?ctxcontractId=L4%3A2274&mfunc=30&ctxnavCtx=C&cfunc=228&ct

我有一种情况,需要从下拉列表中以文本或字符串的形式获取当前选择,并对其进行比较以获得进一步的断言,但是当我尝试getText()时,我会在下拉列表中获得完整的项目列表,如何从下拉列表中获取当前选择的项目

<form id="MODIFY_ATTRIBUTES" class="formList" method="post" action="jfn?ctxcontractId=L4%3A2274&mfunc=30&ctxnavCtx=C&cfunc=228&ctxaccountId=L4%3A1877&oid=L4%3A2042&ctx=L&octx=110&jfnRC=1">
<hr/>
<div class="formListTab">
<fieldset>
<div>
<label class="mandatory" for="p-param-L4:80000">Language</label>
<select id="p-param-L4:80000" name="p-param-L4:80000">
<option value="p-param-L4:80000-L4:12610">English</option>
<option selected="selected" value="p-param-L4:80000-L4:12600">French (Standard)</option>
<option value="p-param-L4:80000-L4:12830">Dutch</option>
</select>
</div>

您正在获取整个Select元素的文本,而不仅仅是所选选项。您可以使用内置函数获取所选选项,然后从中获取文本。使用以下内容:

String selectedOption = new Select(driver.findElement(By.id("p-param-L4:80000"))).getFirstSelectedOption().getText();
但是,如果您想使用xpath。你可以尝试以下方法:

String selectedOption = driver.findElement(By.xpath("//select[@id='p-param-L4:80000']/option[@selected='selected']")).getText();
我建议您使用Id获取您所需的文本

String selectedOption = driver.findElement(By.xpath("//select[@id='p-param-L4:80000']/option[@selected='selected']")).getText();