How to extract the text of the firstselectedoption from a dropdown using Selenium Webdriver through Java

半城伤御伤魂 提交于 2021-01-27 22:10:50

问题


After selecting an option from drop-down. I am trying to get that option displayed in the console. below is my code. But I get

"//[[[[ChromeDriver: chrome on WINDOWS (d5a01776981da5dacfeb89dbbc2e6b52)] -> xpath: //*[@name='airline']]].// -> tag name: option]" 

The tag name is option for dropdown options. I have tried all solutions of selectByXXXX. but nothing seems to work. what would be the right code ?

//airline preference
{
    Select airline = new Select (driver.find Element(By.name("airline"))); //selecting tag
    Thread.sleep(2000); //sleeptime`
    airline.selectByVisibleText("Pangea Air"); //selecting option
    Thread.sleep(2000); //sleep time
    Select airlin = new Select (driver.findElement(By.xpath("//*[@name='airline']"))); //omg
    WebElement s = airlin.getFirstSelectedOption();
    Thread.sleep(2000);
    System.out.println(s);
}

回答1:


getFirstSelectedOption

getFirstSelectedOption() returns the first selected option in this select tag (or the currently selected option in a normal select). NoSuchElementException is thrown if no option is selected.


Seems you were pretty close. Once you select an option through selectByVisibleText() next you can invoke getFirstSelectedOption() to choose the option element selected and finally using getText() you can extract the option text as per the solution below:

  • Code Block:

    Select airline = new Select (driver.find Element(By.name("airline"))); //selecting tag
    airline.selectByVisibleText("Pangea Air"); //selecting option
    WebElement s = airline.getFirstSelectedOption();
    System.out.println(s.getText());
    
  • Console Output:

    Pangea Air
    


来源:https://stackoverflow.com/questions/59794277/how-to-extract-the-text-of-the-firstselectedoption-from-a-dropdown-using-seleniu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!