Be sure to use selenium's waiting, three waiting ways to interpret

insert image description here

​Many people ask, this drop-down box cannot be located, that pop-up box cannot be located... all kinds of positions cannot be located, in fact, there are two kinds of problems in most cases:

  • there is a frame
  • no waiting

As everyone knows, what is the order of your code running speed, and what is the order of browser loading and rendering speed, just like Flash and Bump Man make an appointment to fight monsters, and then Flash asks Bump Man you Why are you still wearing your shoes and not going out? There are 10,000 alpacas flying by in the Bump Man Point Center. The speed of the bullying brother is slow, and the brother will not play with you anymore, so I will throw an exception.

picture

So how can we take care of the slow loading speed of Bump Man? There is only one way, and that is to wait. When it comes to waiting, there are three other ways to wait , let’s listen to the bloggers one by one:

01 Forced waiting

The first and most simple and rude method is to wait for sleep(xx) forcibly, forcing the Flash to wait for xx time, no matter whether Bumpman can keep up with the speed or has already arrived ahead of time, he must wait for xx time.

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)  # 强制等待3秒再执行下一步

print driver.current_url
driver.quit()

This is called forced waiting. Regardless of whether your browser is loaded or not, the program has to wait for 3 seconds. Once the 3 seconds are up, continue to execute the following code. It is very useful for debugging. Sometimes you can wait in the code like this, but it is not recommended. Always using this waiting method is too rigid and seriously affects the execution speed of the program.

02 implicit waiting

The second method is called implicitly waiting, implicitly_wait(xx). The meaning of implicit waiting is: Flash and Bump Man have agreed that no matter where Flash goes, they will wait for Bump Man for xx seconds. When Nei comes, the two of them immediately set off to fight the monsters. If Bump Man doesn't arrive within the specified time, the Flash will go by himself, and naturally wait for Bump Man to throw an exception for you.

Look at the code:

# -*- coding: utf-8 -*-



from selenium import webdriver



driver = webdriver.Firefox()
driver.implicitly_wait(30)  # 隐性等待,最长等30秒
driver.get('https://huilansame.github.io')

print driver.current_url
driver.quit()

Invisible waiting is to set a maximum waiting time. If the webpage is loaded within the specified time, then execute the next step, otherwise wait until the time expires, and then execute the next step.

Note that there is a disadvantage here, that is, the program will wait for the entire page to load, that is, under normal circumstances, you will not execute the next step until you see the small circle in the browser tab bar no longer turns, but sometimes the elements you want on the page The loading has already been completed, but because some js and other things are very slow, I still have to wait until the page is completely completed before I can execute the next step. I want to wait until the elements I want come out, what should I do next? There is a way, it depends on another waiting method provided by selenium-explicit waiting wait.

What needs to be specially explained is: implicit waiting works on the entire driver cycle, so it only needs to be set once. I have seen some people use implicit waiting as a sleep, and it will come everywhere...

03 Dominant waiting

The third method is explicit waiting. WebDriverWait, combined with the until() and until_not() methods of this class, can wait flexibly according to the judgment conditions. Its main meaning is: the program looks at every xx seconds, if the condition is established, then execute the next step, otherwise continue to wait until the set maximum time is exceeded, and then throw TimeoutException.

Let's look at a code example first:

# -*- coding: utf-8 -*-



from selenium import webdriver

from selenium.webdriver.support.waitimport WebDriverWait

from selenium.webdriver.supportimport expected_conditions as EC

from selenium.webdriver.common.byimport By


driver = webdriver.Firefox()
driver.implicitly_wait(10)  # 隐性等待和显性等待可以同时用,但要注意:等待的最长时间取两者之中的大者
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 implicit wait and explicit wait. In other operations, implicit wait plays a decisive role, and explicit wait plays a major role in WebDriverWait..., but it should be noted that the longest waiting time depends on The larger one between the two, in this example is 20, if the implicit waiting time > explicit waiting time, then the longest waiting time of the code is equal to the implicit waiting time.

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

WebDriverWait

The WebDriverWait class of the wait module is an explicit waiting class. Let's first look at its parameters and methods:

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

init

driver: 传入WebDriver实例,即我们上例中的driver

timeout: 超时时间,等待的最长时间(同时要考虑隐性等待时间)
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是当某元素消失或什么条件不成立则继续执行,参数也相同,不再赘述。

After reading the above content, it is basically clear. The calling method is as follows:

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

What needs special attention here is the executable method method parameter in until or until_not. Many people pass in the WebElement object, as follows:

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

This is a wrong usage. The parameters here must be callable, that is, the object must have a call() method, otherwise an exception will be thrown:

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 **is_displayed(), is_enabled(), is_selected()** methods of WebElement, or use your own encapsulated method, then 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.expected_conditions(模块)

The following two conditional classes verify title and verify whether the incoming parameter title is equal to or included in driver.title

title_is

title_contains

The following two conditions verify whether an element appears. The parameters passed in are tuple-type locators, such as (By.ID, 'kw'). As the name implies, one will pass as long as one eligible element is loaded; the other must be all All elements that meet the conditions are loaded.

presence_of_element_located

presence_of_all_elements_located

The following three conditions verify whether the element is visible, the first two incoming parameters are locators of tuple type, and the third incoming WebElement (the first and third are essentially the same)

visibility_of_element_located

invisibility_of_element_located

visibility_of

The following two conditions determine whether a certain text appears in an element, one determines the text of the element, and the other determines the value of the 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, and can be passed in the locator tuple or the positioning method directly: id, name, index or WebElement

frame_to_be_available_and_switch_to_it

The following conditions determine whether an alert appears

alert_is_present

The following conditions determine whether the element is clickable, and pass in the locator

element_to_be_clickable

The following four conditions determine whether an element is selected:

element_to_be_selected(传入WebElement对象)

element_located_to_be_selected(传入locator元组)

element_selection_state_to_be(传入WebElement对象以及状态,相等返回True,否则返回False)

element_located_selection_state_to_be(传入locator以及状态,相等返回True,否则返回False)

The last condition determines whether an element is still in the DOM, passing in the WebElement object can determine whether the page has been refreshed

staleness_of

The above are all 17 conditions, and the combination with until and until_not can achieve a lot of judgments. If you can flexibly package it yourself, it will greatly improve the stability of the script.

Finally: The complete software testing video tutorial below has been organized and uploaded, and friends who need it can get it by themselves【保100%免费】
insert image description here

Software Testing Interview Documentation

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Ali, Tencent, and Byte, and some Byte bosses have given authoritative answers. Finish this set The interview materials believe that everyone can find a satisfactory job.
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/m0_67695717/article/details/132228933
Recommended