【问题标题】:How to print selected option from drowdown by using selenium java?如何使用 selenium java 从下拉列表中打印选定的选项?
【发布时间】:2021-01-14 02:55:21
【问题描述】:

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

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

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

【问题讨论】:

  • 去掉sortBy1的声明,使用WebElement selected=sortBy.getFirstSelectedOption();除非索引的设置导致元素sortBy变成stale,这种情况下你的代码是正确的。
  • 是的,它抛出了陈旧的元素异常,这就是为什么我用另一个对象引用声明它
  • 那么你的代码是正确的。你不能使用同一个对象,因为它已经过时了。但是,您可以使用相同的变量,但再次设置它的值而不是使用 sortBy1 -> sortBy=new Select(driver.findElement(By.xpath("(//select[contains(@title,\"Sort By\")])[1]")));

标签: java selenium selenium-webdriver selenium-chromedriver testng


【解决方案1】:

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

见以下代码:

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;

Reference discussion

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多