繁体   English   中英

如何使用 selenium java 从下拉列表中打印选定的选项?

[英]How to print selected option from drowdown by using selenium java?

从下拉列表中选择选项后只想打印所选选项的值。

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());
            
        }
}

我得到了正确的结果,但我认为这不是写两次选择类的最佳方式,所以你能帮我写得更好吗

选择下拉元素后,您再次使用 find 元素的正确方法,但选择后您应该等待一段时间以使该元素再次可见。

请参阅以下代码:

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());

但是在上面我再次找到了没有为下拉列表创建新变量名的元素,仍然是sortBy 尽管通过初始化,新变量也应该起作用。

不要忘记导入以下内容:

import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

参考讨论

首先,您必须等待元素可见。 其次,使用此代码

Select select = new Select("Element");
WebElement tmp = select.getFirstSelectedOption();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM