簡體   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