[英]How to get selected option using Selenium WebDriver with Java
我想使用 Selenium WebDriver獲取選定的 label或下拉列表的值,然后將其打印在控制台上。
我可以 select 下拉列表中的任何值,但我無法檢索所選值並打印它:
Select select = new
Select(driver.findElement(By.id("MyDropDown"))).selectByVisibleText(data[11].substring(1 , data[11].length()-1));
WebElement option = select.getFirstSelectedOption();
但是我所有的努力都是徒勞的。 我如何獲得選擇的選項?
您應該能夠使用getText()
獲取文本(對於您使用getFirstSelectedOption()
獲得的選項元素):
Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );
完成答案:
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);
在 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
在以下選項上:
WebElement option = select.getFirstSelectedOption();
option.getText();
如果從方法getText()
得到一個空白,則可以使用方法getAttribute
從選項的值中獲取字符串:
WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");
簡答
Select select = new Select(driver.findElement(By.xpath("//select")));
System.out.println("selected items from the dropdown"+ select.getFirstSelectedOption().getText());
var option = driver.FindElement(By.Id("employmentType"));
var selectElement = new SelectElement(option);
Task.Delay(3000).Wait();
selectElement.SelectByIndex(2);
Console.Read();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.