Explanation of Python selenium three waiting Methods: pythonselenium

Source: Internet
Author: User

Explanation of Python selenium three waiting Methods: pythonselenium

I found that too many people will not wait. Today, the bloggers cannot help but tell you the necessity of waiting.

Many people ask in the group that the drop-down box cannot be located, the pop-up box cannot be located... In most cases, there are two problems: frame and wait. I don't know what kind of speed your code is running, but what kind of speed does the browser load and render? It's like the relationship between flash and tomman to beat monsters, then, after flash came back, I asked mongoman why are you still wearing your shoes? In the middle of Myman, 10 thousand alpaca flies in his heart, and the speed of bullying is slow. If he doesn't play with you, he throws an exception.

So how can we take care of the slow loading speed of mongoman? There is only one way to wait. Speaking of equality, there are three other equality methods, and I heard from the bloggers one by one:

1. Force wait

The first and most simple method is to force waiting for sleep (xx) and force xx time such as flash to keep up with the speed, whether or not mongoman can keep up with the speed, must wait for xx time.

Check the Code:

#-*-Coding: UTF-8-*-from selenium import webdriverfrom time import sleepdriver = webdriver. firefox () driver. get ('https: // huilansame. github. io ') sleep (3) # force wait 3 seconds before executing the next print driver. current_urldriver.quit ()

This is called Force wait. No matter whether your browser has been loaded or not, the program has to wait 3 seconds and 3 seconds until it continues to execute the following code, which is useful for debugging, sometimes you can wait in the code like this, but it is not recommended to always use this waiting method, too rigid, seriously affecting the program execution speed.

2. Implicit waiting

The second method is implicit wait, implicitly_wait (xx). The significance of implicit wait is: the arrangement between flash and mongoman, no matter where the flash goes, will wait for mongoman xx seconds, if tomman is here during this time, the two will immediately start to fight monsters. If tomman is not there within the specified time, then the flash will go on his own. Naturally, it will be waiting for tomman to throw an exception for you.

Check the Code:

#-*-Coding: UTF-8-*-from selenium import webdriverdriver = webdriver. firefox () driver. implicitly_wait (30) # implicit wait. The maximum length is 30 seconds. get ('https: // huilansame. github. io ') print driver. current_urldriver.quit ()

The maximum waiting time is set for the invisible wait. If the webpage loading is completed within the specified time, execute the next step. Otherwise, wait until the deadline and then execute the next step. Note that there is a drawback here, that is, the program will wait until the whole page is loaded, that is, normally you will see the small circle in the tab bar of the browser and then execute the next step, however, sometimes the elements that the page wants are already loaded, but because some js and other things are very slow, I still have to wait until the page is complete before proceeding to the next step, what should I do after the elements I want come out? There is a way, it depends on another waiting method provided by selenium-explicitly waiting for wait.

It should be particularly noted that the implicit wait takes effect for the entire driver cycle, so you only need to set it once. I once saw someone using the implicit wait as a sleep, come anywhere...

3. Explicit waiting

The third method is explicit wait. WebDriverWait, in combination with the until () and until_not () methods of this class, can flexibly wait according to the Judgment conditions. It mainly means that the program will take a look every xx seconds. If the condition is true, execute the next step. Otherwise, wait until the maximum time is exceeded, and then throw TimeoutException.

First look at a sample code:

#-*-Coding: UTF-8-*-from selenium import webdriverfrom selenium. webdriver. support. wait import WebDriverWaitfrom selenium. webdriver. support import expected_conditions as ECfrom selenium. webdriver. common. by import Bydriver = webdriver. firefox () driver. implicitly_wait (10) # implicit waiting and explicit waiting can be used at the same time, but note: the maximum waiting time is the driver of the two. get ('https: // huilansame. github. io ') locator = (. 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 implicit waiting and explicit waiting. In other operations, implicit waiting plays a decisive role in WebDriverWait .. explicit wait plays a major role, but note that the longest wait time is determined by the two. In this example, the maximum wait time is 20. If the implicit wait time> explicit wait time, the maximum waiting time of the sentence code is equal to the implicit waiting time.

We mainly use the WebDriverWait class and expected_conditions modules. The following blog will take a closer look at these two modules:

WebDriverWait

The WebDriverWait class of the wait module is a dominant wait class. First, let's take a look at its parameters and methods:

Selenium. webdriver. support. wait. webDriverWait (class) _ init _ driver: input the WebDriver instance, that is, the driver timeout in the previous example: timeout time, the longest wait time (also consider the implicit wait time) poll_frequency: the interval between calling methods in until or until_not. The default value is 0.5 seconds ignored_exceptions: Ignore exception. If an exception in this tuples is thrown during until or until_not calls, the Code is not interrupted, continue to wait. If an exception is thrown out of this tuples, the code is interrupted and an exception is thrown. By default, only NoSuchElementException is supported. Until method: during the waiting period, call the passed method at intervals until the returned value is not False message: If the timeout occurs, a TimeoutException is thrown, and the message is passed in with the exception until_not, until is to continue execution when an element appears or when conditions are true. until_not is to continue execution when an element disappears or when conditions are not true. The parameters are the same and will not be repeated. Method message

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

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

Note that the executable method parameter in until or until_not is described as follows:

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

This is an incorrect usage. The parameter here must be called, that is, the object must have the _ call _ () method. Otherwise, an exception is thrown:

TypeError: 'xxx' object is not callable

Here, you can use various conditions in the expected_conditions module provided by selenium, or use the is_displayed (), is_enabled (), is_selected () Methods of WebElement, you can also use your own encapsulated methods. Next, let's take a look at the conditions provided by selenium:

Expected_conditions

Expected_conditions is a module of selenium, which contains a series of conditions that can be used for judgment: selenium. webdriver. support. the expected_conditions (module) condition class verifies the title and verifies whether the input parameter title is equal to or contained in the driver. the two conditions titletitle_istitle_contains are used to verify whether the element exists. The input parameters are all tuples of the locator type, such as (. ID, 'kw ') as the name implies, a qualified element can be loaded; the other three conditions, presence_of_element_locatedpresence_of_all_elements_located, must be loaded to verify whether the elements are visible. The first two input parameters are locator of the tuples, the third is passed into the WebElement. The first and third are actually the same visibility_of_element_locatedinvisibility_of_element_locatedvisibility_of. The two conditions determine whether a text appears in an element and the text of an element, A valuetext_to_be_present_in_elementtext_to_be_present_in_element_value condition for determining whether a frame can be cut in. You can pass in a locator tuples or directly pass in the positioning method: the condition id, name, index, or marker determines whether alert has the alert_is_present condition to determine whether the element can be clicked, and whether the four conditions locatorelement_to_be_clickable are selected, the first condition is used to pass in the WebElement object, the second is used to pass in the locator tuples, and the third is used to pass in the WebElement object and the State. If the third condition is the same, True is returned. Otherwise, True is returned, otherwise, the final condition of the marker is returned to determine whether an element is still in the DOM. If a WebElement object is input, it can be used to determine whether staleness_of is refreshed on the page.

The above are all 17 conditions, which can be combined with until and until_not to achieve many judgments. If they can be flexibly encapsulated by themselves, the stability of the script will be greatly improved.

I will share these content today. If you have any questions, please leave a message to me and hope to help students in need. Thank you for your support!

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.