Python selenium--must be used selenium wait, three kinds of waiting way to interpret

Source: Internet
Author: User
Tags set time

Found that too many people will not use the waiting, bloggers today really can't help but to tell everyone about the need to wait.

A lot of people in the group asked, this drop-down box is not located, the pop-up box cannot be located ... Various positioning is not, in fact, most of the cases are two kinds of problems: 1 have frame,2 no wait. As everyone knows, your code running speed is what magnitude, and browser load rendering speed is what magnitude, like the flash and bump man about to play monsters, and then after the flash came back to ask the bump-man why you still on the shoes did not go out? Concave and convex man points in the heart 10,000 alpaca fly over, bully brother Slow, brother don't play with you, throw an abnormal altogether.

So how can you take care of the slow loading speed of the bump? There is only one way, that is to wait. Speaking of waiting, there are three kinds of other methods, and listen to the Bo master one by one ways to:

1. Forced wait

The first is also the most simple and rough one way is to force waiting for sleep (xx), the force of the Lightning, such as XX time, whether the bump can keep up with the speed, or has been early, must wait xx time.

Look at the code:

# -*- coding: utf-8 -*-from selenium import webdriverfrom time import sleepdriver = webdriver.Firefox()driver.get(‘https://huilansame.github.io‘)sleep(3) # 强制等待3秒再执行下一步print driver.current_urldriver.quit()

This is called forced wait, regardless of whether your browser is loaded, the program will have to wait 3 seconds, 3 seconds to continue to execute the following code, as debugging is very useful, and sometimes can be in the code such as waiting, but not always use this kind of wait, too rigid, seriously affect program execution speed.

2. Hidden waiting

The second method is called the Hidden Wait, implicitly_wait (xx), the meaning of the hidden wait is: The flash and bump-man agreement, no matter where the flash to, all must wait for the bump man xx seconds, if the bump in this period of time to come, then two people immediately set off to play monsters, if the bump in the specified time, Then the flash himself, that nature will wait for you to throw an exception.

Look at the code:

# -*- coding: utf-8 -*-from selenium import webdriverdriver = webdriver.Firefox()driver.implicitly_wait(30)  # 隐性等待,最长等30秒driver.get(‘https://huilansame.github.io‘)print driver.current_urldriver.quit()

The stealth wait is set to a maximum wait time, if the page load completes within the specified time, then the next step, otherwise wait until the time cutoff, and then perform the next step. Note Here is a disadvantage, that is, the program will always wait for the entire page to load complete, that is, generally you see the browser tab bar that small circle no longer go, will do the next step, but sometimes the page wants the element has been loaded completed, but because the individual JS and other things particularly slow, I still have to wait until the page is complete to perform the next step, and I want to wait for the element I want to come out and what to do next? There is a way, it depends on selenium provide another way of waiting--------explicit waiting wait.

What needs to be specifically explained is: The recessive waits for the whole driver the cycle all to have the function, so as long as set once can, I have seen someone to take the recessive wait as the sleep in use, walks everywhere to come ...

3. Explicit wait

The third method is the explicit wait, webdriverwait, with the class of until () and Until_not () methods, can be based on the conditions of judgment and flexibility to wait. Its main meaning is: The program every XX seconds to see a glance, if the condition is set up, then the next step, otherwise continue to wait until the maximum set time, and then throw timeoutexception.

Let's look at a code example:

#-*-Coding:utf-8-*-From seleniumImport WebdriverFrom selenium.webdriver.support.waitImport webdriverwaitfrom selenium.webdriver.support import expected_conditions Span class= "Hljs-keyword" >as ecfrom selenium.webdriver.common.by import bydriver = Webdriver. Firefox () driver.implicitly_wait (10) # hidden wait and explicit wait can be used simultaneously, But note: Wait for the longest time to take both of the big Driver.get ( ' Https://huilansame.github.io ') locator = (By.link_text,  ' CSDN ') try:webdriverwait (Driver, 20, 0.5 ). Until (ec.presence_of_element_located (locator)) print driver.find_element_by_link_ Text ( ' CSDN '). Get_attribute ( ' href ') finally:driver.close ()           

In the example above, we set the implicit wait and explicit wait, in other operations, the implicit wait plays a decisive role in webdriverwait. The dominant wait plays a major role, but it is important to note that the longest wait time depends on the larger of the two, in this case, 20, if the implicit wait time > Dominant wait time, the maximum wait time for the sentence code is equal to the hidden wait time.

We mainly use the Webdriverwait class and the Expected_conditions module, the following bloggers take a closer look at these two modules:

Webdriverwait

The Webdriverwait class of the wait module is the dominant wait class, which first looks at what parameters and methods it has:

selenium.webdriver.support.wait.WebDriverWait(类)

__init__

driver: 传入WebDriver实例,即我们上例中的drivertimeout: 超时时间,等待的最长时间(同时要考虑隐性等待时间)poll_frequency: 调用until或until_not中的方法的间隔时间,默认是0.5秒ignored_exceptions: 忽略的异常,如果在调用until或until_not的过程中抛出这个元组中的异常,        则不中断代码,继续等待,如果抛出的是这个元组外的异常,则中断代码,抛出异常。默认只有NoSuchElementException。

Until

method: 在等待期间,每隔一段时间(__init__中的poll_frequency)调用这个传入的方法,直到返回值不是Falsemessage: 如果超时,抛出TimeoutException,将message传入异常

Until_not

 与until相反,until是当某元素出现或什么条件成立则继续执行, until_not是当某元素消失或什么条件不成立则继续执行,参数也相同,不再赘述。

Look at the above content is basically clear, the call method is as follows:

WebDriverWait(driver, 超时时长, 调用频率, 忽略异常).until(可执行方法, 超时时返回的信息)

It is important to note here that the executable method parameter in until or Until_not, many people pass in the Webelement object, as follows:

10).until(driver.find_element_by_id(‘kw‘))  # 错误

This is the wrong use, the parameters here must be called, that is, the object must have a __call__() method, or throw an exception:

‘xxx‘ object is not callable

Here, you can use selenium to provide the expected_conditions various conditions in the module, but also can be used webelement, is_displayed() is_enabled() , is_selected() methods, or in their own packaging methods can be, then we look at the selenium to provide the conditions are:

Expected_conditions

Expected_conditions is a module of selenium that contains a set of conditions that can be used to determine:

selenium.webdriver.support.expected_conditions(模块)

The following two conditional classes verify the title, verifying that the passed-in parameter title is equal to or contained in the Driver.title
Title_is
Title_contains

The following two conditions verify that the element is present and the passed in parameters are locator of the tuple type, such as (by.id, ' kw ')
As the name implies, a single element that meets the criteria is loaded, and the other must be loaded with all eligible elements.
presence_of_element_located
presence_of_all_elements_located

The following three conditions verify that the element is visible, the first two incoming parameters are locator of the tuple type, and the third incoming webelement
The first one and the third one are the same in nature.
visibility_of_element_located
invisibility_of_element_located
Visibility_of

The following two conditions determine whether a piece of text appears in an element, the text of a judging element, the value of a judging element
Text_to_be_present_in_element
Text_to_be_present_in_element_value

The following conditions determine whether the frame can be cut in, can pass into the locator tuple or directly into the positioning mode: ID, name, index or webelement
Frame_to_be_available_and_switch_to_it

The following conditions determine if an alert appears
Alert_is_present

The following conditions determine whether the element can be clicked, incoming locator
Element_to_be_clickable

The following four conditions determine whether an element is selected, the first condition passes into the Webelement object, and the second incoming locator tuple
The third incoming Webelement object and state, equal returns True, otherwise returns false
Fourth incoming locator and state, equal returns True, otherwise false
element_to_be_selected
element_located_to_be_selected
Element_selection_state_to_be
Element_located_selection_state_to_be

The last condition determines whether an element is still in the DOM and passes in the Webelement object to determine if the page is refreshed.
Staleness_of

The above is all 17 condition, with until, until_not combination can achieve a lot of judgments, if you can flexibly package, will greatly improve the stability of the script.

Python selenium--must be used selenium wait, three kinds of waiting way interpretation (turn)

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.