您的位置:首页 > 大数据 > 人工智能

Selenium - Waits

2016-05-13 11:33 489 查看
WebDriver can generally be said to have a blocking API. Because it is an out-of-process library thatinstructs the browser what to do, and because the
web platform has an intrinsicly asynchronous nature, WebDriver doesn't track the active, real-time state of the DOM. This comes with some challenges that we will discuss here.
From experience, most intermittents that arise from use of Selenium and WebDriver are connected torace conditions that occur between the browser and
the user's instructions. An example could be that the user instructs the browser to navigate to a page, then gets a no such element error when trying to find an element.
Consider the following document:

<!doctype html>
<meta charset=utf-8>
<title>Race Condition Example<title>

<script>
var initialised = false;
window.addEventListener("load", function() {
var newElement = document.createElement("p");
newElement.textContent = "Hello from JavaScript!";
document.body.appendChild(newElement);
initialised = true;
});
</script>
The WebDriver instructions might look innocent enough:

driver.navigate("file:///race_condition.html")
el = driver.find_element_by_tag_name("p")
assert el.text == "Hello from JavaScript!"


The issue here is that the default page
load strategy used in WebDriver listens for thedocument.readyState to change to 
"complete"
 before returning from the call to navigate. Because the
p
 element is added after the document has completed
loading, this WebDriver script might be intermittent. It “might” be intermittent because no guarantees can be made about elements or events that trigger asynchronously without explicitly waiting—or blocking—on those events.
Fortunately, using the normal instruction set available on the WebElement interface—such
asWebElement.click and WebElement.sendKeys—are guaranteed to be synchronous, in that the function calls won't return (or the callback won't trigger in callback-style languages) until the the command has been completed in the browser. The
advanced user interaction APIs, Keyboard and Mouse,
are exceptions as they are explicitly intended as “do what I say” asynchronous commands.
Waiting is having the automated task execution elapse a certain amount of time before continuing with the next step.
To overcome the problem of race conditions between the browser and your WebDriver script, most Selenium clients ships with a wait package. When employing
a wait, you are using what is commonly referred to as an explicit
wait.


Explicit Wait

Explicit waits are available to Selenium clients for imperative, procedural languages. They allow your code to halt program execution, or freezing
the thread, until the condition you pass it resolves. The condition is called with a certain frequency until the timeout of the wait is elapsed. This means that for as long as the condition returns a falsy value, it will keep trying and keep waiting.
Since explicit waits allow you to wait for a condition to occur, they make a good fit for synchronising the state between the browser and its DOM, and your
WebDriver script.
To remedy our buggy instruction set from earlier, we could employ a wait to have the findElement call wait until the dynamically added element from
the script has been added to the DOM:

from selenium.webdriver.support.ui import WebDriverWait

def document_initialised(driver):
return driver.execute_script("return initialised")

driver.navigate("file:///race_condition.html")
WebDriverWait(driver).until(document_initialised)
el = driver.find_element_by_tag_name("p")
assert el.text == "Hello from JavaScript!"


We pass in the condition as a function reference that the wait will run repeatedly until its return value is truthy. A “truthful” return value
is anything that evaluates to boolean true in the language at hand, such as a string, number, a boolean, an object (including a WebElement), or a populated (non-empty) sequence or list. That means an empty list evaluates to false. When the
condition is truthful and the blocking wait is aborted, the return value from the condition becomes the return value of the wait.
With this knowledge, and because the wait utility ignores no such element errors by default, we can refactor our instructions to be more concise:
from selenium.webdriver.support.ui import WebDriverWait

driver.navigate("file:///race_condition.html")
el = WebDriverWait(driver).until(lambda d: return d.find_element_by_tag_name("p"))
assert el.text == "Hello from JavaScript!"

In that example we pass in an anonymous function (but we could also define it explicitly as we did earlier so it may be reused). The first and only argument
that is passed to our condition is always a reference to our driver object, WebDriver (called d in the example). In a multi-threaded environment you should be careful to operate on the driver reference passed in to the condition rather than
the reference to the driver in the outer scope.
Because the wait will swallow no such element errors that are raised when the element isn't found, the condition will retry until the element is found.
Then it will take the return value, a WebElement, an pass it back through to our script.
If the condition fails, e.g. a truthful return value from the condition is never reached, the wait will throw/raise an error/exception called a timeout
error.

Options

The wait condition can be customised to match your needs. Sometimes it's unnecessary to wait the full extent of the default timeout, as the penalty for not
hitting a successful condition can be expensive.
The wait lets you pass in an argument to override the timeout:
WebDriverWait(driver, timeout=3).until(some_condition)

Expected Conditions

Because it's quite a common occurence to have to synchronise the DOM and your instructions, most clients also come with a set of predefined expected conditions.
As might be obvious by the name, they are conditions that are predefined for frequent wait operations.
The conditions available in the different language bindings vary, but this is a non-exhaustive list of a few:
alert is presentelement existselement is visibletitle containstitle iselement stalenessvisible textYou can refer to the API documentation for each client binding to find an exhaustive list of expected conditions:
Java's 
org.openqa.selenium.support.ui.ExpectedConditions
 package
Python's 
selenium.webdriver.support.expected_conditions
 package
.NET's 
OpenQA.Selenium.Support.UI.ExpectedConditions
 type


Implicit Waiting

There is a second type of wait that is distinct from explicit
waits called implicit waiting. By implicitly waiting, WebDriver to poll the DOM for a certain duration when trying to find any element. This can be useful when certain elements on the webpage will not be available immediately and needs
some time to load.
Implicit waiting for elements to appear is disabled by default and will need to be manually enabled on a per-session basis. Mixing explicit
waits and implicit waiting will cause unintended consequences, namely waits sleeping for the maximum time even if the element is available or condition is true.
Warning: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds
and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available.
The default setting is 0, meaning disabled. Once set, the implicit wait is set for the life of the session.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));

FluentWait

FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.
User may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
FluentWait<By> fluentWait = new FluentWait<By>(By.tagName("TEXTAREA"));
fluentWait.pollingEvery(100, TimeUnit.MILLISECONDS);
fluentWait.withTimeout(1000, TimeUnit.MILLISECONDS);
fluentWait.until(new Predicate<By>() {
public boolean apply(By by) {
try {
return browser.findElement(by).isDisplayed();
} catch (NoSuchElementException ex) {
return false;
}
}
});
browser.findElement(By.tagName("TEXTAREA")).sendKeys("text to enter");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Selenium Waits