简体   繁体   English

如何使用 selenium 中的下拉选项获取下拉选项值

[英]How to get dropdown option value using dropdown option in selenium

I'm developing a automation that needs to access the first (and only one) dropdown value.我正在开发一种需要访问第一个(也是唯一一个)下拉值的自动化。 I want to get this "Unavailable date" value to do a validation in the future.我想获得这个“不可用日期”值以在将来进行验证。 This is the HTML:这是 HTML:

<div class = "content-box-wrapper">
    <fieldset>
        <li>
            <label>Select a time</label>
    
            <div>
                <select name = "idAgenda" id="hourSelected">
                    <option value>Unavailable date</option>
                </select>
            </div>
        </li>
    </fieldset>    
</div> 
import org.openqa.selenium.support.ui.Select;
Select hours = new Select(driver.findElement(By.id("hoursSelected")));


hours.selectByIndex(1);
hours.selectByVisibleText("Unavailable date");
hours.selectByValue("Unavailable date")

Since it's in a Select tag you can use the following import and select by index or value.由于它位于 Select 标记中,因此您可以使用以下导入并按索引或值进行选择。

You need to use the below xPath to get the selected value of drop-down.您需要使用下面的xPath来获取下拉列表的选定值。

//select[@id='hourSelected']/option

In case, if drop-down is having multiple values then if it have selected tag for selected value.万一,如果下拉菜单有多个值,那么如果它为选定值selected了标签。 Please write xPath as below,请按如下方式编写xPath

HTML

<option value="">Unavailable date1</option>
<option selected="" value="">Unavailable date2</option>
<option value="">Unavailable date3</option>

xPath

//select[@id='hourSelected']/option[@selected]

I got it using getText() method:我使用 getText() 方法得到它:

WebElement disponibilidade = chrome.findElement(By.xpath("//*[@id=\"hourSelected\"]"));
String text1 = disponibilidade.getText();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM