如何通过 Java 使用 Selenium Webdriver 从下拉列表中提取 firstselectedoption 的文本 [英] How to extract the text of the firstselectedoption from a dropdown using Selenium Webdriver through Java

查看:25
本文介绍了如何通过 Java 使用 Selenium Webdriver 从下拉列表中提取 firstselectedoption 的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从下拉列表中选择一个选项后.我试图让该选项显示在控制台中.下面是我的代码.但我得到

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]" 

标签名称是下拉选项的选项.我已经尝试了 selectByXXXX 的所有解决方案.但似乎没有任何效果.什么是正确的代码?

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);
}

推荐答案

getFirstSelectedOption

getFirstSelectedOption() 返回此选择标记中的第一个选定选项(或普通选择中当前选定的选项).如果没有选择任何选项,则抛出 NoSuchElementException.

看来你很接近了.一旦你通过 selectByVisibleText() 选择了一个选项,接下来你可以调用 getFirstSelectedOption() 来选择被选中的选项元素,最后使用 getText() 你可以按照以下解决方案提取选项文本:

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
    

  • 这篇关于如何通过 Java 使用 Selenium Webdriver 从下拉列表中提取 firstselectedoption 的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆