简体   繁体   中英

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:

<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.

You need to use the below xPath to get the selected value of drop-down.

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

In case, if drop-down is having multiple values then if it have selected tag for selected value. Please write xPath as below,

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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