如何在 Selenium 中等待下拉框中的選項充滿?


我們可以在 select 標籤中等待選項由 Selenium 填充。這可以透過同步中的 顯式等待 概念來實現。顯式等待是基於元素的 預期條件 進行設計的。

為了等待這些選項,我們將在顯式等待時間內驗證 presenceOfNestedElementsLocatedBy 是否可用。我們將在 try catch 塊中實現整個驗證。

我們來看看 Continents 下拉框中是否有可供選擇的選項。ExpectedCondition 與 WebDriverWait 一起用於顯式等待。

下拉框的 HTML 程式碼。

示例

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;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SelectOptWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://tutorialspoint.tw/selenium/selenium_automation_practice.htm");
      //expected condition presenceOfNestedElementsLocatedBy on options
      WebDriverWait w = new WebDriverWait(driver,3);
      try {
         w.until(ExpectedConditions
         .presenceOfNestedElementsLocatedBy
         (By.xpath("//select[@name='continents']"), By.tagName("option")));
         // identify dropdown
         WebElement l = driver.findElement(By.xpath("//select[@name='continents']"));
         // select option by Select class
         Select s = new Select(l);
         // selectByVisibleText to choose an option
         s.selectByVisibleText("Africa");
      }
      catch(Exception e) {
         System.out.println("Options not available");
      }
      driver.quit();
   }
}

更新於:2020-11-30

3K+ 次瀏覽

開始你的 事業

完成課程獲得認證

開始學習
廣告