[英]How to print selected option from drowdown by using selenium java?
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.选择下拉元素后,您再次使用 find 元素的正确方法,但选择后您应该等待一段时间以使该元素再次可见。
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
.但是在上面我再次找到了没有为下拉列表创建新变量名的元素,仍然是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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.