DOM 要素の待機

スクリプトは、DOM で使用できない UI コンポーネントにアクセスしていることがあります。この原因は、次の図に示すように、ネットワーク遅延である可能性があります。つまり、DOM がアクセスする準備ができていません。

ネットワーク遅延図

この問題は、明示的または暗黙的いずれかの待機を使用して回避できます。次のセクションでは、さまざまなタイプの待機とそれぞれの使用するタイミングについて説明します。

Explicit Versus Implicit

The WebDriver function driver.implicitly_wait(n) configures WebDriver for the remainder of a session. If you try to access an element that is not available, WebDriver will retry for up to n seconds to find that element in the DOM. This simple approach is often sufficient to make your scripts work reliably.

In the diagram below, the WebDriver retries to click Button 2 until it's available.

Explicit Wait Diagram

An explicit wait is code that requires a certain condition to occur before continuing to execute code. Although you may be tempted to use time.sleep() to wait for an element to be available, you should avoid doing this. Instead, use the WebDriver API methods given in 5.1. Explicit Waits of the Selenium Python Bindings documentation that enable you to wait for expected conditions.

In the diagram below, the explicit wait stipulates to click Button 2 (action) only when the button is available (the condition).

Explicit Wait Diagram