サーチ…


Selenium WebDriverで待機するタイプ

任意のWebアプリケーションを実行している間は、読み込み時間を考慮する必要があります。コードがまだロードされていない要素にアクセスしようとすると、WebDriverは例外をスローし、スクリプトは停止します。

Waitには3つのタイプがあります -

  • 暗黙の待機
  • 明示的な待機
  • 流暢な待ち時間

明示的な待機は特定の部分でのみ使用されるのに対し、暗黙の待機はプログラム全体で待機時間を設定するために使用されます。


暗黙の待機

暗黙的な待機とは、WebDriverに、すぐに利用可能でない要素を見つけようとすると、一定の時間、DOMをポーリングするように指示することです。暗黙の待機とは、基本的に、指定されたWeb要素がWebDriverが探しているものがない場合に、WebDriverに通知したい待機時間を通知する方法です。既定の設定は0です。設定されると、暗黙の待機がWebDriverオブジェクトインスタンスの有効期間に設定されます。暗黙的な待機は、次のスニペットを使用してコードのインスタンス化部分で宣言されます。

Javaの例:

driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// You need to import the following class - import java.util.concurrent.TimeUnit;

C#の例:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(15));

この場合、UI(DOM)で指定された要素が利用できない場合、WebDriverが15秒待つように指示します。


明示的な待機

一部の要素が読み込まれるまでに時間がかかる場合があります。このような場合の暗黙の待機の設定は意味がありません。ブラウザがすべての要素に対して同じ時間だけ不必要に待機し、自動化時間が長くなるからです。明示的な待機は、いくつかの特定の要素について暗黙的な待機をバイパスすることによってここで役立ちます。

明示的な待機とは、特定のWeb要素に限定されたインテリジェントな待機です。明示的な待機を使用すると、基本的にWebDriverに最大時間を伝えることは、それが断念するまでにX単位の時間を待つことです。

明示的な待機は、WebDriverWaitクラスとExpectedConditionsクラスを使用して行われます。次の例では、idがusernameの要素が次のコマンドに進む前に表示されるまで10秒間待つものとします。ここに手順があります。

Javaの例:

//Import these two packages:
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

//Declare a WebDriverWait variable. In this example, we will use myWaitVar as the name of the variable.
WebDriverWait myWaitVar = new WebDriverWait(driver, 30);

//Use myWaitVar with ExpectedConditions on portions where you need the explicit wait to occur. In this case, we will use explicit wait on the username input before we type the text tutorial onto it.
myWaitVar.until(ExpectedConditions.visibilityOfElementLocated(By.id(“username”)));
driver.findElement(By.id(“username”)).sendKeys(“tutorial”);

ExpectedConditionsクラスには、要素を待つためのいくつかの事前定義された共通条件があります。 Javaバインディングにおけるこれらの条件のリストを表示するには、 ここをクリックしてください。

C#の例:

using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.PhantomJS;

// You can use any other WebDriver you want, such as ChromeDriver.
using (var driver = new PhantomJSDriver())
{
    driver.Navigate().GoToUrl("http://somedomain/url_that_delays_loading");

    // We aren't going to use it more than once, so no need to declare this a variable.
    new WebDriverWait(driver, TimeSpan.FromSeconds(10))
        .Until(ExpectedConditions.ElementIsVisible(By.Id("element-id")));

    // After the element is detected by the previous Wait, 
    // it will display the element's text
    Console.WriteLine(driver.FindElement(By.Id("element-id")).Text);
}

この例では、要素が表示されるまで10秒間待機します。要素がタイムアウト後に表示されません場合は、webdriverをがスローされますWebDriverTimeoutException

注:要素が10秒のタイムアウト前に表示されている場合、システムはすぐに処理を続行します。


流暢な待機

暗黙的および明示的な待機とは異なり、流暢な待機は2つのパラメータを使用します。タイムアウト値とポーリング頻度。たとえば、タイムアウト値が30秒、ポーリング頻度が2秒であるとします。 WebDriverは、タイムアウト値(30秒)まで2秒ごとに要素をチェックします。結果のないタイムアウト値を超えた後、例外がスローされます。以下は、流暢な待機の実装を示すサンプルコードです。

Javaの例:

Wait wait = new FluentWait(driver).withTimeout(30, SECONDS).pollingEvery(2, SECONDS).ignoring(NoSuchElementException.class);


WebElement testElement = wait.until(new Function() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.id("testId"));
    }
});

流暢な待機を使用するもう1つの利点は、待機中に特定のタイプの例外(例:NoSuchElementExceptions)を無視できることです。これらのすべての規定のため、AJAXアプリケーションや要素の読み込み時間が頻繁に変動するシナリオでは、流暢な待機が役立ちます。流暢な待機の戦略的な使用は、自動化の取り組みを大幅に改善します。


さまざまな種類の明示的な待機条件

明示的な待機では、条件が発生することを期待します。たとえば、要素がクリック可能になるまで待機したいとします。

ここにいくつかの一般的な問題のデモンストレーションがあります。

注意:これらすべての例では、 classnamexpathlink texttag namecssSelectorなどのロケータとしてByを使用できます。


要素が表示されるまで待ちます

たとえば、Webサイトの読み込みに時間がかかる場合は、ページの読み込みが完了し、WebDriverに要素が表示されるまで待つことができます。

C#

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("element-id")));

Java

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

要素がもう見えなくなるまで待つ

前と同じですが、逆です。

C#

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.Id("element-id")));

Java

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("element-id")));

指定された要素にテキストが存在するまで待ちます。

C#

IWebElement element = driver.FindElement(By.Id("element-id"));

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.TextToBePresentInElement(element, "text"));

Java

WebElement element = driver.findElement(By.id("element-id"));

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.textToBePresentInElement(element, "text"));

上のリンクに行くと、そこにすべての待ち状態が表示されます。

これらの待機条件の使用の違いは、入力パラメータにあります。

つまり、WebElementの入力パラメータがWebElementの場合、WebElementを渡す必要があることを意味します。入力パラメータとしてByロケータを使用する場合、要素ロケータを渡す必要があります。

どんな種類の待機条件を使用するかを賢明に選択してください。

Ajaxリクエストの完了を待つ

C#

using OpenQA.Selenium
using OpenQA.Selenium.Chrome;
using System.Threading;

namespace WebDriver Tests
{
    class WebDriverWaits
    {
        static void Main()
        {
            IWebDriver driver = new ChromeDriver(@"C:\WebDriver");
            
            driver.Navigate().GoToUrl("page with ajax requests");
            CheckPageIsLoaded(driver);

            // Now the page is fully loaded, you can continue with further tests.
        }

        private void CheckPageIsLoaded(IWebDriver driver)
        {
            while (true)
            {
                bool ajaxIsComplete = (bool)(driver as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0");
                if (ajaxIsComplete)
                    return;
                Thread.Sleep(100);
            }
        }
    }
}

この例は、ajaxリクエストが行われたページで役に立ちます。ここではIJavaScriptExecutorを使用して独自のJavaScriptコードを実行します。 whileループの中にあるので、 ajaxIsComplete == trueになるまで実行し続け、return文が実行されます。

jQuery.active0ことを確認して、すべてのajaxリクエストが完了したことを確認し0 。これは、新しいajaxリクエストが作成されるjQuery.activeがインクリメントされ、リクエストを補完するたびにデクリメントされるため、 jQuery.active == 0すべてのAjaxリクエストが完了しなければならないと推測できるからです。

流暢待ち

Fluent Waitは、 明示的な待機( WebDriverWait )のスーパークラスであり、wait関数の引数を受け入れることができるため、より構成可能です。それを避けるのがベストプラクティスなので、私は暗黙の待機を渡します。

使用法(Java):

Wait wait = new FluentWait<>(this.driver)
        .withTimeout(driverTimeoutSeconds, TimeUnit.SECONDS)
        .pollingEvery(500, TimeUnit.MILLISECONDS)
        .ignoring(StaleElementReferenceException.class)
        .ignoring(NoSuchElementException.class)
        .ignoring(ElementNotVisibleException.class);

WebElement foo = wait.until(ExpectedConditions.presenceOfElementLocated(By.yourBy));

// or use your own predicate:
WebElement foo = wait.until(new Function() {
  public WebElement apply(WebDriver driver) {
    return element.getText().length() > 0;
  }
});

Explicit waitをデフォルトで使用すると、デフォルトでFluentWait<WebDriver>になりますFluentWait<WebDriver> DEFAULT_SLEEP_TIMEOUT = 500; NotFoundExceptionを無視しNotFoundException

流暢な待機

各FluentWaitインスタンスは、条件を待つ最大時間と、条件を確認する頻度を定義します。さらに、ユーザーは、ページ上の要素を検索するときにNoSuchElementExceptionsなど、待機中に特定のタイプの例外を無視するように待機を構成することができます。これは、ドライバに関連付けられています。

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS) //actuall wait for the element to pe present
.pollingEvery(5, SECONDS) //selenium will keep looking for the element after every 5seconds
.ignoring(NoSuchElementException.class); //while ignoring this condition
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("username"));


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow