当前位置:网站首页>Skills that testers must know: Selenium's three waiting ways are interpreted clearly
Skills that testers must know: Selenium's three waiting ways are interpreted clearly
2022-07-07 08:51:00 【Software testing】
Too many people can't wait , Bloggers today can't help but tell you the necessity of waiting . Many people ask , This drop-down box cannot be located 、 That pop-up box can't be located … All kinds of positioning cannot be found , In fact, in most cases, there are two problems :
Yes frame
No waiting
Little imagine , What is the speed of your code , What is the order of magnitude of browser loading and rendering speed , It's like flash and pummelo make an appointment to fight monsters , Then the flash came back and asked why you were still wearing your shoes ? Ten thousand alpacas flew by in his heart , Bullying brother is slow , I won't play with you , Throw an unusual pick .
So how can we take care of the slow loading speed ? There's only one way , That's waiting . Speaking of waiting , There are three other methods , Let's listen to the blogger :
01、 Mandatory waiting
The first and simplest way is to force waiting sleep(xx), Force flash to wait xx Time , Whether we can keep up with the speed or not , Or has it arrived ahead of time , We all have to wait 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) # Mandatory waiting 3 Seconds before proceeding to the next step
print driver.current_url
driver.quit()
This is called forced waiting , Whether your browser is loaded or not , The program has to wait 3 second ,3 One second to , Continue with the following code , Useful as a debugging tool , Sometimes you can wait like this in the code , However, it is not recommended to always wait in this way , Too rigid , Seriously affect the execution speed of the program .
02、 The recessive waiting
The second method is called implicit waiting ,implicitly_wait(xx), The meaning of implicit waiting is : Flash and Portman have an appointment , Wherever flash goes , All have to wait xx second , If Portman comes during this time , Then they immediately set out to fight the monster , If you don't arrive within the specified time , Then the flash goes by himself , Naturally, I'll wait for Portman to throw you an exception .
Look at the code :
# -*- coding: utf-8 -*-
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(30) # The recessive waiting , Longest etc 30 second
driver.get('https://huilansame.github.io')
print driver.current_url
driver.quit()
Stealth wait is set to a maximum wait time , If the web page is loaded within the specified time , Then go to the next step , Otherwise, wait until the deadline , Then go to the next step .
Note that there is a drawback , That is, the program will wait for the whole page to load , In other words, generally you see that the small circle in the browser tab bar doesn't rotate any more , To take the next step , But sometimes the elements the page wants are already loaded , But because of the individual js Things like that are very slow , I still have to wait until the page is complete to go to the next step , I want to wait until the elements I want come out and what to do next ? Is there a way to , It depends on selenium Another way to wait —— Explicit wait wait 了 .
One thing to note is that : Recessive waiting for the whole driver All the cycles work , So just set it once , I've seen people treat hidden waiting as sleep In use , Come wherever you go …
03、 Explicit wait
The third way is to wait ,WebDriverWait, With this kind of until() and until_not() Method , We can wait flexibly according to the judging conditions . Its main meaning is : Program every xx Take a second , If the conditions hold , Then go to the next step , Otherwise, keep waiting , Until the set maximum time is exceeded , Then throw TimeoutException.
Let's start with a code example :
# -*- 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) # Implicit waiting and explicit waiting can be used at the same time , But should pay attention to : The longest waiting time 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 implicit waiting and explicit waiting , In other operations , Implicit waiting plays a decisive role , stay WebDriverWait… Explicit waiting plays a major role in , But here's the thing : The longest waiting time depends on the greater of the two , In this case 20, If the hidden waiting time > Explicit waiting time , Then the maximum waiting time of the sentence code is equal to the implicit waiting time .
We mainly use WebDriverWait Class and expected_conditions modular , Now the blogger takes you to take a closer look at these two modules :
WebDriverWait
wait Modular WebDriverWait Class is an explicit wait class , Let's take a look at its parameters and methods :
selenium.webdriver.support.wait.WebDriverWait( class )
init
driver: Pass in WebDriver example , In our example above driver
timeout: Timeout time , The longest time to wait ( At the same time, consider the implicit waiting time )
poll_frequency: call until or until_not The interval time of the method in , The default is 0.5 second
ignored_exceptions: Ignored exception , If you're calling until or until_not Throw the exception in this tuple in the process of ,
Then do not interrupt the code , Continue to wait for , If you throw an exception out of this tuple , Then interrupt the code , Throw an exception . Only by default NoSuchElementException
until
method: While waiting , Every once in a while (__init__ Medium poll_frequency) Call this incoming method , Until the return value is not Falsemessage: If the timeout , Throw out TimeoutException, take message Incoming exception
until_not
And until contrary ,until When an element appears or what conditions hold, it will continue to execute ,
until_not When some element disappears or some condition is not tenable, continue to execute , The parameters are the same , I won't repeat .
After reading the above contents, it is basically clear , The method to invoke is as follows :
WebDriverWait(driver, Time out period , Call frequency , Ignore exceptions ).until( Executable method , Information returned on timeout )
Here is the special note until or until_not The executable method in method Parameters , A lot of people introduced WebElement object , as follows :
WebDriverWait(driver, 10).until(driver.find_element_by_id(‘kw’)) # error
This is the wrong way to use , The parameters here must be callable , That is, this object must have call() Method , Otherwise, an exception will be thrown :
TypeError: ‘xxx’ object is not callable
ad locum , You can use it. selenium Provided expected_conditions Various conditions in the module , It can also be used. WebElement Of **is_displayed() 、is_enabled()、is_selected() ** Method , Or you can do it in your own way , So let's take a look at selenium What are the conditions provided :
expected_conditions
expected_conditions yes selenium A module of , It contains a series of conditions that can be used to judge :
selenium.webdriver.support.expected_conditions( modular )
The following two condition classes validate title, Verify the parameters passed in title Whether equal to or contained in driver.title
title_is
title_contains
The following two conditions verify whether the element appears , The parameters passed in are of tuple type locator, Such as (By.ID, ‘kw’), seeing the name of a thing one thinks of its function , As long as a qualified element is loaded, it passes through ; The other one has to load all the 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 of tuple type locator, The third one came in WebElement( The first and the third are essentially the same )
visibility_of_element_located
invisibility_of_element_located
visibility_of
The following two conditions determine whether a piece of text appears in an element , Of a judging element text, Of a judging element value
text_to_be_present_in_element
text_to_be_present_in_element_value
The following conditions determine frame Is it possible to cut in , Can be introduced into locator Tuple or direct incoming location method :
id、name、index or WebElement
frame_to_be_available_and_switch_to_it
The following conditions determine whether there is alert appear
alert_is_present
The following conditions determine whether the element can be clicked , Pass in locator
element_to_be_clickable
The following four conditions determine whether an element is selected :
element_to_be_selected( Pass in WebElement object )
element_located_to_be_selected( Pass in locator Tuples )
element_selection_state_to_be( Pass in WebElement Object and state , Equal return True, Otherwise return to False)
element_located_selection_state_to_be( Pass in locator And the state , Equal return True, Otherwise return to False)
The last condition determines whether an element is still DOM in , Pass in WebElement object , You can judge whether the page is refreshed
staleness_of
It's all 17 individual condition, And until、until_not A combination can make a lot of judgments , If it can be flexibly packaged by itself , Will greatly improve the stability of the script .
The house needs to be built layer by layer , Knowledge needs to be learned at one point one . We should lay a good foundation in the process of learning , More hands-on practice , Don't talk much , The last dry goods here ! I stayed up late to sort out the stages ( function 、 Interface 、 automation 、 performance 、 Test open ) Skills learning materials + Practical explanation , Very suitable for studying in private , It's much more efficient than self-study , Share with you .
Get off w/x/g/z/h: Software testing tips dao
Typing is not easy , If this article is helpful to you , Click a like, collect a hide and pay attention , Give the author an encouragement . It's also convenient for you to find it quickly next time .
边栏推荐
- xray的简单使用
- [Chongqing Guangdong education] audio visual language reference materials of Xinyang Normal University
- let const
- [Chongqing Guangdong education] organic electronics (Bilingual) reference materials of Nanjing University of Posts and Telecommunications
- 求有符号数的原码、反码和补码【C语言】
- Greenplum6.x监控软件搭建
- What are the advantages of commas in conditional statements- What is the advantage of commas in a conditional statement?
- Lenovo hybrid cloud Lenovo xcloud: 4 major product lines +it service portal
- How to add a mask of a target in a picture
- Calling the creation engine interface of Huawei game multimedia service returns error code 1002, error message: the params is error
猜你喜欢
[Yu Yue education] basic reference materials of electrical and electronic technology of Nanjing Institute of information technology
[Yugong series] February 2022 U3D full stack class 006 unity toolbar
Arm GIC (IV) GIC V3 register class analysis notes.
leetcode135. Distribute candy
Quick sorting (detailed illustration of single way, double way, three way)
为什么要选择云原生数据库
联想混合云Lenovo xCloud:4大产品线+IT服务门户
指针进阶,字符串函数
Greenplum6.x-版本变化记录-常用手册
Count sort (diagram)
随机推荐
为不同类型设备构建应用的三大更新 | 2022 I/O 重点回顾
AVL balanced binary search tree
let const
快速集成认证服务-HarmonyOS平台
Why choose cloud native database
Tips for using jeditabletable
You should use Google related products with caution
Other 7 features of TCP [sliding window mechanism ▲]
channel. Detailed explanation of queuedeclare parameters
Implementation of navigation bar at the bottom of applet
【MySQL】数据库进阶之触发器内容详解
mysql分区讲解及操作语句
【踩坑】nacos注册一直连接localhost:8848,no available server
Interpolation lookup (two methods)
Count sort (diagram)
Mock.js用法详解
Data type - floating point (C language)
opencv 将16位图像数据转为8位、8转16
Enterprise manager cannot connect to the database instance
Opencv converts 16 bit image data to 8 bits and 8 to 16