如何使用硒的webdriver与Java获取所选选项(How to get selected opt

2019-06-27 00:49发布

我在硒新手,我坚持在这里:

我希望得到一个下降 的选定标签或值的下降用Selenium的webdriver,然后打印控制台

我可以选择任何降下来的值,但我不能够检索所选择的值,并打印出来。

Select select = new 
Select(driver.findElement(By.id("MyDropDown"))).selectByVisibleText(data[11].substring(1 , data[11].length()-1));
WebElement option = select.getFirstSelectedOption();

但我所有的努力白费去任何帮助,将不胜感激。 提前致谢 :)

Answer 1:

你应该能够得到使用文本getText()对你有使用选项元素getFirstSelectedOption()

Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );


Answer 2:

完成了答案:

String selectedOption = new Select(driver.findElement(By.xpath("Type the xpath of the drop-down element"))).getFirstSelectedOption().getText();

Assert.assertEquals("Please select any option...", selectedOption);


Answer 3:

在硒的Python是:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select

def get_selected_value_from_drop_down(self):
    try:
        select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
        return select.first_selected_option.get_attribute("value")
    except NoSuchElementException, e:
        print "Element not found "
        print e


Answer 4:

在下面的选项:

WebElement option = select.getFirstSelectedOption();
option.getText();

如果从方法getText()你会得到一个空白,你可以从使用方法选项的值的字符串getAttribute

WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");


Answer 5:

var option = driver.FindElement(By.Id("employmentType"));
        var selectElement = new SelectElement(option);
        Task.Delay(3000).Wait();
        selectElement.SelectByIndex(2);
        Console.Read();


文章来源: How to get selected option using Selenium WebDriver with Java