」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 Java 在 Selenium WebDriver 中選擇下拉值?

如何使用 Java 在 Selenium WebDriver 中選擇下拉值?

發佈於2024-11-07
瀏覽:295

How to Select Dropdown Values in Selenium WebDriver with Java?

使用Java 在Selenium WebDriver 中選擇下拉值

對於Selenium WebDriver 的初學者來說,從下拉清單中選擇值可能是一個常見的挑戰。以下是有效解決這種情況的綜合指南:

HTML 結構:

首先,讓我們考慮下拉式選單的HTML 結構:

元素標識:

要使用Selenium WebDriver 標識下拉列表,您可以使用By.id() 定位器:

WebElement dropdown = driver.findElement(By.id("periodId"));

建立選擇物件:

現在,從下拉式選單,您需要建立選擇物件:

Select dropdownSelection = new Select(dropdown);

Select dropdownSelection = new Select(dropdown);

Select dropdownSelection = new Select(dropdown);

  • 選擇選項:
  • 有了Select物件後,您可以透過三種方式選擇選項:
dropdownSelection.selectByVisibleText("Last 52 Weeks");
透過可見文字選擇:
    透過選項的可見文字選擇:
  • dropdownSelection.selectByVisibleText("最近52 週");
dropdownSelection.selectByVisibleText("Last 52 Weeks");
selectByIndex:
    依選項索引選擇:
  • dropdown. 1); // 從0 開始的索引,因此「最近52 週」位於索引1
dropdownSelection.selectByVisibleText("Last 52 Weeks");
selectByValue:

透過選項的value 屬性選擇:

dropdownSelection.selectByValue("l52w");

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("periodId")));

如果遇到「元素目前不可見」錯誤,可能會是由於下拉式選單最初被隱藏。您可以使用 WebDriverWait 等待元素變得可見,然後再與其互動:

WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("periodId")));

How to Select Dropdown Values in Selenium WebDriver with Java? 
結論:

透過這些技術,您可以毫不費力地選擇下拉值使用Java 的Selenium WebDriver,即使在具有隱藏或動態元素的複雜場景中也是如此。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3