Python selenium three kinds of waiting ways to interpret _python

Source: Internet
Author: User

Find too many people will not use the waiting, bloggers today is really can't help to tell you the need to wait.

A lot of people in the group asked, the dropdown box is not positioned, the pop-up box is not positioned ... A variety of positioning is not, in fact, in most cases is two kinds of problems: 1 frame,2 did not add to wait. As you know, the speed of your code is what level, and the browser load rendering speed is what magnitude, like the flash and the concave-convex about good to play monsters, and then the Flash after the return of the call asked why you still wear shoes did not go out? Concave-convex in the heart of 10,000 alpaca fly, bullying brother Speed slow, brother don't play with you, throw an abnormal Shing.

So how can you take care of the slow loading speed of the bump? There's only one way, that's waiting. Speaking of waiting, there are three kinds of law, and listen to Bo main one by one:

1. Mandatory waiting

The first and most simple one way is to force waiting for sleep (xx), forced to let the flash, such as XX time, regardless of whether the concave-convex can keep up with speed, or has been early, must wait for xx time.

Look at the code:

#-*-Coding:utf-8-*-from
Selenium import Webdriver to time
import sleep

driver = Webdriver. Firefox ()
driver.get (' Https://huilansame.github.io ') Sleep

(3) # force wait 3 seconds before performing next

print Driver.current_url
Driver.quit ()

This is called forced waiting, whether your browser is finished loading, the program will have to wait 3 seconds, 3 seconds to go, continue to execute the following code, as debugging is useful, and sometimes also in the code such as waiting, but do not recommend the total use of this waiting way, too rigid, seriously affect the speed of program execution.

2. Recessive wait

The second method is called recessive wait, implicitly_wait (xx), the meaning of the recessive wait is: Flash and bump man agreed to, no matter where the flash to go, should wait for the bump xx seconds, if the concave-convex in this period of time to come, then two people immediately set out to play monsters, if the concave Mann in the stipulated time, Then the Lightning man goes to his own, and the nature waits for the bump to give you an unusual throw.

Look at the code:

#-*-Coding:utf-8-*-from
Selenium import webdriver

driver = webdriver. Firefox ()
driver.implicitly_wait (30) # Hidden wait, longest wait 30 seconds
driver.get (' Https://huilansame.github.io ')

print Driver.current_url
Driver.quit ()

Stealth waiting is set up for a maximum wait time, if the page is loaded within the specified time, execute the next step, or wait until the time expires, and then proceed to the next step. Note that there is a drawback, 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 will not turn, the next step, but sometimes the page wants the element has been completed in the load, 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 elements I want to do next. There is a way, this depends on the selenium provides another way to wait-the dominant waiting for wait.

Need to specifically note that: The hidden waiting for the entire driver cycle, so as long as the set can, I have seen someone to the hidden waiting as a sleep in use, go where all come to ...

3. Explicit waiting

The third approach is to have the explicit wait, webdriverwait, and the Until () and Until_not () method of the class to be able to wait flexibly according to the conditions of judgment. Its main meaning is: The program every XX seconds to look at, if the condition is set up, then perform the next step, otherwise continue to wait until the maximum set of time, and then throw timeoutexception.

Let's look at a code example:

#-*-Coding:utf-8-*-from
Selenium import webdriver from
selenium.webdriver.support.wait import webdriverwait From
selenium.webdriver.support import expected_conditions as EC from
selenium.webdriver.common.by import by< C5/>driver = Webdriver. Firefox ()
driver.implicitly_wait (10) # Recessive wait and explicit wait can be used simultaneously, but note that the longest time to wait takes the big
driver.get (' https:// Huilansame.github.io ')
locator = (by.link_text, ' CSDN ')

try:
  webdriverwait (Driver, 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 dominance wait, in other operations, the implicit wait plays a decisive role in the webdriverwait. In the dominant wait, but note that the longest wait time depends on the big one between the two, in this case 20, if the implicit wait time > The dominant wait time, then the longest wait time of the code is equal to the implicit wait time.

We mainly use the Webdriverwait class and 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 waiting class, which first looks at its parameters and methods:

Selenium.webdriver.support.wait.WebDriverWait (Class)

__init__
  driver: Incoming Webdriver instance, that is, the driver
  in our previous example Timeout: timeout, maximum waiting time (while considering implicit wait time)
  poll_frequency: The interval between calls to methods in until or Until_not, default is 0.5 seconds
  ignored_exceptions : The ignored exception, if the exception in this tuple is thrown during the call to until or Until_not, the
      code is not interrupted, and if the exception outside this tuple is thrown, break the code and throw an exception. Default only Nosuchelementexception.

until
  method: During the wait period, the incoming methods are called at intervals until the return value is not false message
  : If timeout, throw timeoutexception, pass message to the exception

Until_not and until on the contrary, until is when an element appears or what conditions are set up to continue execution,
    Until_not is when an element disappears or what condition is not established then continue to execute, the parameter is same, no longer repeat. Method Message
  

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

Webdriverwait (driver, timeout length, call frequency, ignore exception). Until (executable method, information returned by timeout)

A special note here is the executable method parameter in until or Until_not, many people pass in the Webelement object, as follows:

Webdriverwait (Driver). Until (driver.find_element_by_id (' kw ')) # error

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

TypeError: ' xxx ' object is not callable

Here, you can use the various conditions in the Expected_conditions module provided by selenium, or you can use the Webelement is_displayed (), is_enabled (), is_selected () method, Or use your own encapsulation method, then let's take a look at what the selenium offers:

Expected_conditions

Expected_conditions is a selenium module that contains a series of criteria that can be used for judgment: selenium.webdriver.support.expected_conditions (module) The two criteria classes validate the title to verify that the passed in argument title is equal to or contained in Driver.title Title_is title_contains the two-person condition verifies that the element appears, and the incoming arguments are locator of the tuple type, such as (by.id , ' kw ') as the name suggests, a qualified element is passed when it is loaded; another must all eligible elements be loaded to presence_of_element_located Presence_of_all_elements_
Located these 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 and third are the same in essence visibility_of_element_located Invisibility_of_element_located visibility_of The two-person condition to determine whether a paragraph of text appears in an element, the text of a judgment element, the value of a judgment element Text_to_be_present_
In_element Text_to_be_present_in_element_value This condition to determine whether the frame can be cut in, can be passed into the locator tuple or directly into the positioning mode: ID, name, index or webelement Frame_to_be_available_and_switch_to_it this condition to determine whether an alert appears alert_is_present this condition to determine whether the element is clickable, incoming locator Element_to_be_
Clickable these four conditions determine whether the element is selected, the first condition passes into the Webelement object, the second incoming locator the third incoming Webelement object and the state, equality returns TRUE, or False Fourth incoming locator and state, equality 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, passing in the Webelement object to determine if the page is refreshed staleness_of

 

Above 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.

Today to share these content, what questions you can leave a message for me to communicate, I hope to help the students in need. Thank you for your support to this site!

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.