Python+selenium notes (10): element wait mechanism

Source: Internet
Author: User

(i) preface

A sudden resource constraint or network delay may result in the target element not being found, and the test report shows that the test failed. In this case, a delay mechanism is required to match the speed of the script with the response speed of the program, and Webdriver provides both implicit and explicit wait mechanisms.

(ii) Implicit wait

Once the implicit wait time is set, it acts on the entire life cycle of the Webdriver instance (which takes effect for all element lookups), and after setting the implicit wait time, Webdriver continuously detects and searches the DOM for a certain amount of time, To make it easier to find one or more elements that are not immediately loaded successfully and available. The default time for an implicit wait is 0. Webdriver uses implicitly_wait () to set the wait time, in seconds. More than waiting time has not been found, reported nosuchelementexception abnormal.

# set the time-out to 10 seconds

Driver.implicitly_wait (10)

(iii) Explicit Wait

Webdriver provides webdriverwait classes and Expected_conditions modules to implement explicit waits. The display waits more intelligently than the implicit wait. Display wait is set a precondition, in the waiting time, every time after checking whether the precondition is satisfied, the next step is fulfilled, the timeout is reported timeoutexception exception.

(iv) webdriverwait class

Webdriverwait (Driver, timeout, poll_frequency=poll_frequency, ignored_exceptions=None)
Driver: Browser Driver instance
Timeout: Wait time, per second
Poll_frequency: Check once every few times, default 0.5 seconds
Ignored_exceptions: Ignored exception, default only Nosuchelementexception
Until methods and Until_not methods:
Until (method, message="): means the method to be executed (to be executed once every time during the wait time) until the return value is true and the timeout is reported timeoutexception exception, Message will pass in exception (message parameter is optional)

Until_not (method, message="): Until the return value is false, the other and until are the same

(v) expected_conditions Module

The Expected_conditions module provides a variety of well-defined preconditions that need to be used with webdriverwait.

Expected wait condition (pre-condition)

Simple description

Element_to_be_clickable (Locator)

Parameter: Locator, refers to a group (by,locator)

For example: Webdriverwait (driver,10). Until (Expected_conditions.element_to_be_clickable ((By.name,' one ')))
The following are all in this way, only the preconditions are different, the parameters may be different
Webdriverwait (driver,10). Until ()
The element waiting to be found is visible and available so that it can be clicked to return the anchored element

element_to_be_selected (Locator)
Wait until the element is selected
invisibility_of_element_located (Locator)

Wait for an element to be invisible or nonexistent in the DOM

presence_of_all_elements_located (Locator)

Waits for at least one locator lookup element to appear in the Web page, returning a set of elements

presence_of_element_located (Locator)

The element that waits for the locator to find appears in the Web page, or can be found in the DOM, returning an element that is anchored to

Text_to_be_present_in_element (Locator,text)
Parameters: text, specified literal
Wait for the element to be positioned with the specified text information
Title_contains (title)
Parameter: Title, which is the string to verify the title contains
Waits for the page header to contain the specified string, returns True if successful, or false
Title_is (title)
Parameter: Title, the caption to check
Wait for page title to match expected, return true on success, or false
Visibility_of (Element)
Parameter: element, which refers to a component
The wait element appears in the DOM, is visible, and the width and height are greater than 0 and become visible, returning an element (the same one)
visibility_of_element_located (Locator)
The wait element appears in the DOM, is visible, and the width and height are greater than 0 and become visible, returning an element
Alert_is_present ()
Determine if a warning window exists

(vi) expected_conditions Example

The following code, try: section, each part is independently available (I just verify that the usage of the different preconditions is commented out). In addition, there is only a description of how the method is used (the function of the method) and does not explain the use of the scene (such as whether it is necessary or not).

1  fromSeleniumImportWebdriver2  fromSelenium.webdriver.support.uiImportwebdriverwait3  fromSelenium.webdriver.supportImportexpected_conditions4  fromSelenium.webdriver.common.byImport by5 6Driver =Webdriver. Firefox ()7 Driver.maximize_window ()8Driver.get ('https://www.cnblogs.com/')9 Ten #Try: One ##等待博客园首页的 the "Look for" button is visible and available A #search_btn = webdriverwait (driver,10). Until (Expected_conditions.element_to_be_clickable (By.CLASS_NAME, ' Search_btn ' ))) - #Print (Search_btn.get_attribute (' value ')) -  the #Try: - #Login_area = driver.find_element_by_css_selector (' #login_area ') - #login = login_area.find_element_by_link_text (' login ') - #Login.click () + #Remember_me = driver.find_element_by_id (' Remember_me ') - #Remember_me.click () + ##等待直到登录页面的复选框被选中 A #webdriverwait (Driver). Until (expected_conditions.element_located_to_be_selected (by.id, ' Remember_me '))  at  - #Try: - #search_file = driver.find_element_by_id (' zzk_q ') - #search_btn = driver.find_element_by_class_name (' search_btn ') - #search_file.send_keys (' python ') - #Search_btn.click () in ##网页标题是否包含 python - #webdriverwait (Driver). Until (expected_conditions.title_contains (' Python ')) to  + Try: -Search_file = driver.find_element_by_id ('zzk_q') the     #checks whether an element appears in the DOM, is visible, and is greater than 0 *Search_file = webdriverwait (driver,10). Until (expected_conditions.visibility_of (search_file) ) $     Print(Search_file)Panax Notoginseng finally: -Driver.quit ()

(vii) Example (custom preconditions)

The Expected_conditions class provides a variety of well-defined preconditions (expected wait conditions), and you can also customize preconditions by webdriverwait when there are no preconditions to match.

The following is a partial comment that comes with the Webdriverwait class.

class webdriverwait (object):     def __init__ (Self, driver, timeout, poll_frequency=poll_frequency, ignored_exceptions=None):         """            Example: from            selenium.webdriver.support.ui import webdriverwait \ n            element = webdriverwait ( Driver). Until (Lambda x:x.find_element_by_id ("Someid") \ n            is_disappeared = webdriverwait (Driver, 30, 1, ( elementnotvisibleexception). \ \ n                        until_not (lambda x:x.find_element_by_id ("Someid"). is_displayed ())        """

Example: (Wait for the blog Park Personal homepage (click on the homepage of the garden to jump to the page) the drop-down menu has 5 options)

#lambda表达式其实就是一个匿名函数, the left side of the colon can be understood as the function name and parameters, the right can be understood as the return value of the function, the specific can be Baidu Python lambda

 fromSeleniumImportWebdriver fromSelenium.webdriver.support.uiImportwebdriverwait fromSelenium.webdriver.support.uiImportSelectprofile=Webdriver. Firefoxprofile (R'C:\Users\quanhua\AppData\Roaming\Mozilla\Firefox\Profiles\tnwjkr4m.selenium') Driver=Webdriver. Firefox (Profile) Driver.maximize_window () Driver.get ('https://home.cnblogs.com/')Try:    #wait for a drop-down menu in the blog Park Personal home page with 5 options availableWebdriverwait (driver,10). Until (LambdaL:len (Select (l.find_element_by_id ('sel_application'). Options) = = 5)finally: Driver.quit ()

(eight) Summary

Applying element-wait mechanisms is essential for building highly stable and reliable tests. In the process of use, should try to avoid the implicit wait and display waiting for mixed use. As for the implicit waiting and display of the advantages and disadvantages of waiting, reading on and on the Internet is generally more recommended to use the display wait, but I have tried it, for the time being do not see how much difference in the speed of operation (perhaps after a relatively rich project experience, then back to say that the implicit wait and show the pros and cons of waiting).

Python+selenium notes (10): element wait mechanism

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.