web-dev-qa-db-ja.com

JavaでSelenium WebDriverを使用して選択したオプションを取得する方法

選択したラベルを取得または値ドロップダウン Selenium WebDriverを使用してからprintconsole =。

ドロップダウンから値を選択することはできますが、選択した値を取得して印刷することはできません。

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

しかし、私の努力はすべて無駄でした。選択したオプションを取得するにはどうすればよいですか?

29
Aditi

getText()を使用してテキストを取得できるはずです(getFirstSelectedOption()を使用して取得したオプション要素の場合):

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

答えを完成させる:

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);
18
Bhuvan

Seleniumでは、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
4
Riaz Ladhani

次のオプション:

_WebElement option = select.getFirstSelectedOption();
option.getText();
_

メソッドgetText()から空白を取得する場合、メソッドgetAttributeを使用してオプションの値から文字列を取得できます。

_WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");
_
2
Miguel
var option = driver.FindElement(By.Id("employmentType"));
        var selectElement = new SelectElement(option);
        Task.Delay(3000).Wait();
        selectElement.SelectByIndex(2);
        Console.Read();
0
Madhu Ragi