Selenium2+python Automation 38-Explicit Wait (webdriverwait)

Source: Internet
Author: User
Tags iterable

Objective:

Adding too much sleep to the script can affect the execution speed of the script, although the implicit wait method of the Implicitly_wait () method saves a considerable amount of time.

But once some JS on the page can not be loaded (in fact, the interface elements come out), the upper left corner of the icon has been spinning, this time will be waiting.

First, the parameter explanation

1. There are three main parameters here:

Class Webdriverwait (object):d River, timeout, poll_frequency

2.driver: Returns an instance of the browser, this does not need to say more

3.timeout: Total duration of timeout

4.poll_frequency: Loop to query the gap time, default 0.5 seconds

The following is the source code explanation document (case one is the element appears, one is the element disappears)
def __init__ (self, driver, timeout, poll_frequency=poll_frequency, ignored_exceptions=none):
"" "Constructor, takes a Webdriver instance and timeout in seconds.

: Args:
-Driver-instance of Webdriver (Ie, Firefox, Chrome or Remote)
-Timeout-number of seconds before timing out
-Poll_frequency-sleep interval between calls
By default, it is 0.5 second.
-Ignored_exceptions-iterable structure of exception classes ignored during calls.
By default, it contains nosuchelementexception only.

Example:
From selenium.webdriver.support.ui import webdriverwait \ n
element = webdriverwait (driver, ten). Until (Lambda x:x.find_element_by_id ("Someid") \ n
is_disappeared = webdriverwait (Driver, 1, (elementnotvisibleexception)). \ n
Until_not (Lambda x:x.find_element_by_id ("Someid"). Is_displayed ())
"""

Second, the element appears: until ()

1.until There is a lambda function, this syntax look at the python document

2. Take Baidu input box as an example

Three, the element disappears: Until_not ()

1. Determine if the element disappears, is returned ture, no return False

Note: This method is not adjusted, temporarily put this

Iv. Reference Code:

# Coding:utf-8
From selenium import Webdriver
From selenium.webdriver.support.wait import webdriverwait

Driver = Webdriver. Firefox ()
Driver.get ("http://www.baidu.com")
# Wait 10 seconds, default 0.5 seconds to ask
Webdriverwait (Driver). Until (Lambda x:x.find_element_by_id ("kw")). Send_keys ("Yoyo")

# Determine if the ID is KW element disappears
is_disappeared = webdriverwait (Driver, 10, 1). \
Until_not (Lambda x:x.find_element_by_id ("kw"). Is_displayed ())
Print is_disappeared

Five, webdriverwait source

1.WebDriverWait mainly provides two methods, one is until (), the other is Until_not ()

The following is the source of the comments, interested in the small partners can see

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# Distributed with the additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); Except in compliance
# with the License. Obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# unless required by applicable or agreed to writing,
# Software distributed under the License is distributed in an
# ' As is ' BASIS, without warranties OR CONDITIONS of any
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

Import time
From selenium.common.exceptions import nosuchelementexception
From selenium.common.exceptions import timeoutexception

poll_frequency = 0.5 # How long-to-sleep inbetween calls to the method
Ignored_exceptions = (nosuchelementexception,) # EXCEPTIONS ignored during calls to the method


Class Webdriverwait (object):
def __init__ (self, driver, timeout, poll_frequency=poll_frequency, ignored_exceptions=none):
"" "Constructor, takes a Webdriver instance and timeout in seconds.

: Args:
-Driver-instance of Webdriver (Ie, Firefox, Chrome or Remote)
-Timeout-number of seconds before timing out
-Poll_frequency-sleep interval between calls
By default, it is 0.5 second.
-Ignored_exceptions-iterable structure of exception classes ignored during calls.
By default, it contains nosuchelementexception only.

Example:
From selenium.webdriver.support.ui import webdriverwait \ n
element = webdriverwait (driver, ten). Until (Lambda x:x.find_element_by_id ("Someid") \ n
is_disappeared = webdriverwait (Driver, 1, (elementnotvisibleexception)). \ n
Until_not (Lambda x:x.find_element_by_id ("Someid"). Is_displayed ())
"""
Self._driver = Driver
Self._timeout = Timeout
Self._poll = poll_frequency
# avoid the divide by zero
If Self._poll = = 0:
Self._poll = poll_frequency
exceptions = List (ignored_exceptions)
If Ignored_exceptions is not None:
Try
Exceptions.extend (ITER (ignored_exceptions))
Except TypeError: # ignored_exceptions is not iterable
Exceptions.append (ignored_exceptions)
Self._ignored_exceptions = tuple (exceptions)

def __repr__ (self):
Return ' <{0.__module__}. {0.__name__} (session= "{1}") > '. Format (
Type (self), self._driver.session_id)

def until (self, method, message= "):
"" "Calls the method provided with the driver as an argument until the \
Return value is not False. "" "
Screen = None
StackTrace = None

End_time = Time.time () + self._timeout
While True:
Try
Value = Method (Self._driver)
If value:
return value
Except Self._ignored_exceptions as exc:
Screen = GetAttr (exc, ' screen ', None)
StackTrace = getattr (exc, ' StackTrace ', None)
Time.sleep (Self._poll)
If Time.time () > End_time:
Break
Raise TimeoutException (message, screen, stacktrace)

def until_not (self, method, message= "):
"" "Calls the method provided with the driver as an argument until the \
return value is False. ""
End_time = Time.time () + self._timeout
While True:
Try
Value = Method (Self._driver)
If not value:
return value
Except Self._ignored_exceptions:
Return True
Time.sleep (Self._poll)
If Time.time () > End_time:
Break
Raise TimeoutException (Message)
The study process has encountered the question, may add selenium (Python+java) QQ Group Exchange: 232607095

Selenium+python Advanced Tutorial "published:selenium webdriver based on Python source case

(Purchase this book to send a PDF version)

Selenium2+python Automation 38-Explicit Wait (webdriverwait)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.