问题
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