just want to print the value of selected option after selecting the option from dropdown .
package Webbasics;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class ecommerce {
public static void main(String args[]) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C:\\Program Files\\selenium\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://live.demoguru99.com/index.php/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[@id=\"nav\"]//li[1]/a")).click();
Select sortBy=new Select(driver.findElement(By.xpath("(//select[contains(@title,\"Sort By\")])[1]")));
sortBy.selectByIndex(1);
Select sortBy1=new Select(driver.findElement(By.xpath("(//select[contains(@title,\"Sort By\")])[1]")));
WebElement selected=sortBy1.getFirstSelectedOption();
System.out.println(selected.getText());
}
}
I am getting proper result but i think its not the best way of writing select class two times so can you help me to write in a better way
You have correct way with find element again after select the dropdown element, but after selected you should wait a while to make the element visible again.
See the following code:
Select sortBy = new Select(driver.findElement(By.xpath("(//select[contains(@title,'Sort By')])[1]")));
sortBy.selectByIndex(1);
//wait here
WebDriverWait wait = new WebDriverWait(driver, 20);
sortBy = new Select(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//select[contains(@title,'Sort By')])[1]"))));
System.out.println(sortBy.getFirstSelectedOption().getText());
But above I find again the element without creating a new variable name for the dropdown, still sortBy
. Although with initialization the new variables should work too.
Don't forget to import the following:
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
Firstly, you have to wait element visible. Secondly, use this code
Select select = new Select("Element");
WebElement tmp = select.getFirstSelectedOption();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.