[英]How to get selected option using Selenium WebDriver with Java
[英]Get selected option using Selenium WebDriver with Java
我是Selenium WebDriver的新手。 我正在測試一個下拉列表。 這是我用來從下拉菜單中選擇項目的代碼。
Select dropdown = new Select(driver.findElement(By.xpath("//select")));
dropdown.selectByValue("FEM");
這工作正常,但是我需要的是將所選項目作為文本。 例如,在value = FEM
,文本顯示為女性。 我需要獲取文本,因為“選定值”是女性。
我搜索了一些文章,但這些都沒有。 請幫忙。 :)
Select
具有getFirstSelectedOption()
方法。 從那里可以使用getText()
Select dropdown = new Select(driver.findElement(By.xpath("//select")));
dropdown.selectByValue("FEM");
WebElement option = dropdown.getFirstSelectedOption();
String text = option.getText();
您可以使用element1.selectByVisibleText(value);
如果要使用文本而不是值來設置選項
如果要獲取值,請使用element1.getAllSelectedOptions().get(0).getText()
或element1.getFirstSelectedOption()
而不是使用dropdown.selectByvalue("FEM")
使用dropdown.selectByVisibleText("FEM")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.