Python selenium three ways of waiting for interpretation

  • 2020-05-10 18:26:28
  • OfStack

Finding that too many people can't wait, the blogger today couldn't help but talk about the need to wait.

A lot of people ask in the group, the drop-down box is not located, the popup box is not located... All kinds of localization can not, in fact, in most cases, there are only two kinds of problems: 1 has frame, 2 does not add wait. But I don't know, what is the speed of your code, and what is the speed of the browser loading rendering speed, like the flash and bump man agreed to fight monsters, and then the flash came back and asked bump man why you still put on your shoes did not go out? Bump man points in the heart of 10,000 alpaca flew, bullying brother slow, brother do not play with you, throw an unusual drop pick.

So how to take care of bump man slow loading speed? There's only one way, and that's to wait. When it comes to waiting, there are three more ways to wait. Let's listen to the blogger's 11 ways:

1. Force a wait

The first and simplest way to do this is to force sleep(xx) to wait for the flash to wait for xx, whether or not bump man can keep up or has arrived early, he must wait for xx.

Look at the code:


# -*- coding: utf-8 -*-
from selenium import webdriver
from time import sleep

driver = webdriver.Firefox()
driver.get('https://huilansame.github.io')

sleep(3) #  Mandatory waiting 3 Let's do it in seconds 1 step 

print driver.current_url
driver.quit()

This is called forced wait, no matter whether your browser is loaded, the program will have to wait 3 seconds, 3 seconds to 1, continue to execute the following code, as a debugging is very useful, sometimes you can also wait in the code like this, but it is not recommended to always use this way of waiting, too rigid, seriously affect the speed of the program execution.

2. Hidden waiting

The second method is called the recessive waiting, implicitly_wait (xx), is the significance of implicit wait: flash and bump mann agreed well, no matter where flash, will bump xx seconds, such as if the bump mann during this time, is two people started to play the monster, if bump mann didn't arrive within the given time, the flash to himself, that nature is waiting for the bump mann give you throw exceptions.

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()

Invisible wait is to set a maximum wait time, if the page is loaded within the specified time, then execute the next step, otherwise 1 wait until the time expires, and then execute the next step. Note there is a drawback, that is, the program will 1 straight for the whole page load is complete, also is one kind case you see the small circle of browser tabs no longer turn, will perform under step 1, but sometimes page want elements early in the loaded, but because of such things as individual js particularly slow, I still have to wait until page complete execution of step 1, I think after I came out of the elements to next step 1? Yes, it depends on another way of waiting provided by selenium -- explicit waiting for wait.

It should be noted that the recessive wait works for the entire driver cycle, so you only need to set it once. I have seen people use the recessive wait as sleep, and they will use it everywhere.

3. Explicit waiting

The third method is the explicit wait, WebDriverWait, which, when combined with the until() and until_not() methods of this class, allows you to wait flexibly depending on your criteria. Its main meaning is: the program looks at it every xx second. If the condition is correct, it performs the next step. Otherwise, it continues to wait until the set maximum time is exceeded, and then throws TimeoutException.

Let's start with 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

driver = webdriver.Firefox()
driver.implicitly_wait(10) #  Implicit wait and explicit wait can be used at the same time, but it is important to note that the longest wait is the greater of the two 
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 above example, we set up the implicit wait and the explicit wait. In other operations, the implicit wait plays a decisive role in WebDriverWait.. The dominant wait plays a major role in this case, but it should be noted that the maximum wait time depends on the larger of the two, in this case 20, if the recessive wait time > Explicit wait time, the maximum wait time of the code is equal to the implicit wait time.

We mainly use WebDriverWait class and expected_conditions module. The blogger takes you to have a closer look at the two modules below:

WebDriverWait

The WebDriverWait class of wait module is an explicit wait class. Let's see what parameters and methods it has:


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

__init__
  driver:  The incoming WebDriver An instance, as in our example above driver
  timeout:  Timeout, maximum wait time (also consider implicit wait time) 
  poll_frequency:  call until or until_not The interval time of the method in the default is 0.5 seconds 
  ignored_exceptions:  Ignore the exception if in the call until or until_not To throw an exception in this tuple, 
       If an exception is thrown outside this tuple, the code is broken and an exception is thrown. By default only NoSuchElementException . 

until
  method:  During the wait, every once in a while 1 The incoming method is called for a period of time until the return value is not False
  message:  If timeout, throw TimeoutException That will be message The incoming abnormal 

until_not  with until On the contrary, until When an element is present or something is true, 
    until_not When an element disappears or a condition fails, it continues with the same parameters. 
  method
  message

After reading the above content, it is basically clear that the method is as follows:

WebDriverWait(driver, timeout duration, call frequency, ignore exceptions).until(executable method, information returned when timeout occurs)

Special attention should be paid to the executable method method parameter in until or until_not. Many people pass the WebElement object as follows:

WebDriverWait(driver, 10).until(driver.find_element_by_id ('kw'))   # error

This is a wrong usage, the parameter 1 here must be callable, that is, this object 1 must have a method of s 99en__ (), otherwise an exception will be thrown:

TypeError: 'xxx' object is not callable

Here, you can use the expected_conditions module provided by selenium, is_displayed(), is_enabled(), is_selected() method of WebElement, is_enabled(), is_selected() method of WebElement, or you can use your own method of encapsulation, so let's take a look at the conditions provided by selenium:

expected_conditions


expected_conditions is selenium the 1 Two modules containing 1 Series of conditions that can be used for judgment: 

selenium.webdriver.support.expected_conditions (modules) 

 These two conditional classes validate title , validating the parameters passed in title Whether equal to or contained in driver.title
title_is
title_contains

 Both conditions verify that the element is present and that the parameters passed in are of tuple type locator , such as (By.ID, 'kw')
 As the name implies, 1 As long as a 1 The qualified elements are loaded and passed; On the other 1 All elements that meet the criteria must be loaded 
presence_of_element_located
presence_of_all_elements_located

 this 3 The first two passed parameters are of type tuple locator In the first 3 An incoming WebElement
 The first 1 And the first 3 The essence of it is 1 The sample of 
visibility_of_element_located
invisibility_of_element_located
visibility_of

 These two people are conditioned to determine whether a piece of text is present in an element, 1 Of the elements text . 1 Of the elements value
text_to_be_present_in_element
text_to_be_present_in_element_value

 The conditional judgment frame Whether you can cut in, you can pass in locator Tuples or directly passed in: id , name , index or WebElement
frame_to_be_available_and_switch_to_it

 This condition determines whether or not alert appear 
alert_is_present

 This condition determines whether the element is clickable and passed in locator
element_to_be_clickable

 this 4 Conditions to determine whether an element is selected, no 1 Conditional pass in WebElement The object, the first 2 An incoming locator tuples 
 The first 3 An incoming WebElement Object and state, equal returns True Otherwise return False
 The first 4 An incoming locator And the state, equal return True Otherwise return False
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be

 The last 1 Individual conditional judgment 1 Is the element still there DOM The incoming WebElement Object to determine whether the page has been refreshed 
staleness_of

The above is all 17 condition. The combination of until and until_not can achieve a lot of judgment. If you can encapsulate it flexibly, it will greatly improve the stability of the script.

Today, I will share these contents. If you have any questions, please leave me a message to communicate with me. I hope I can help the students in need. Thank you for your support!


Related articles: