当前位置:网站首页>Selenium has three waiting methods (forced waiting, implicit waiting, and display waiting)
Selenium has three waiting methods (forced waiting, implicit waiting, and display waiting)
2022-07-03 21:02:00 【Little brother said test】
1、 Mandatory waiting (sleep)
from time import sleep
sleep(3) # Mandatory waiting 3 second
shortcoming : because Web The speed of loading depends on the hardware being tested 、 Network speed 、 Server response time and other factors . If the waiting time is too long , It's easy to waste time , If the waiting time is too short, it may result in web You haven't loaded the required location yet element, And an error is reported .
Because the waiting time cannot be determined , Use too much sleep Will affect the running speed , Greatly reduce efficiency , Therefore, it is recommended to use less forced waiting in the test .
2、 An implicit wait ( implicitly_wait)
# An implicit wait 10s
driver.implicitly_wait(10)
brief introduction : Implicit waiting is global and targeted at all elements , Set the waiting time such as 10 second , If 10 Seconds to appear , Then continue down , Otherwise, throw it out of order . It can be understood that 10 Within seconds , Keep refreshing to see if the element is loaded .
Use scenarios : Implicit wait only needs to be declared once , It is usually declared after opening the browser . After the statement to the whole drvier The life cycle of , There is no need to repeat the statement . There is a problem with implicit waiting , 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 , You still have to wait until the page is complete before you go to the next step .
3、 According to wait ( expected_conditions)
brief introduction : Show that waiting is for an element alone , Set a waiting time such as 5 second , every other 0.5 Check whether it appears every second , If in 5 Seconds before any time , Then continue down , Generally, it is necessary to cooperate with this kind of until() and until_not() Methods used together , Until the set maximum time is exceeded , Then throw a timeout error TimeoutException, Here are some of the most common methods :
1. Judge element Whether or not visible :visibility_of_element_located(locator) ( Visible represents element Non hidden , also element Neither width nor height is equal to 0)
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
# Example
target = EC.visibility_of_element_located(By.ID,'user')
# coordination until() Use ( Wait for the element to be visible )
# 5 Express Maximum timeout , Default in seconds ; 1 Indicates the interval step of detection , While waiting , Every once in a while ( Default 0.5 second ), call until or until_not The method in , Until it comes back True or False.
WebDriverWait(driver, 5, 1).until(EC.visibility_of_element_located(By.ID,'user'))
# coordination until_not() Use ( Wait for the element to be invisible )
WebDriverWait(driver, 5, 1).until_not(EC.visibility_of_element_located(By.ID,'user'))
# Encapsulated as a function in a class
def wait_eleLocated(self, loc, timeout=30, poll_frequency=0.5, model=None):
"""
:param loc: Element location expression ; A tuple type , The way of expression ( Element location type , Element positioning method ), Example :(By.ID, "kw")
:param timeout: Timeout time
:param poll_frequency: Polling frequency
:param model: Wait for failure , Screenshot operation , The function annotation to be expressed in the picture file
:return:None
"""
self.logger.info(f' wait for "{model}" Elements , Positioning mode :{loc}')
try:
start = datetime.now()
WebDriverWait(self.driver, timeout, poll_frequency).until(EC.visibility_of_element_located(loc))
end = datetime.now()
self.logger.info(f' wait for "{model}" Duration :{end - start}')
except TimeoutException:
self.logger.exception(f' wait for "{model}" Element failed , Positioning mode :{loc}')
# Screenshot
self.save_webImgs(f" Waiting elements [{model}] Something unusual happened ")
raise
2. Judge a certain element Whether it is loaded into dom Trees :presence_of_element_located(locator) ( It doesn't mean that element It must be visible )
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
target = EC.presence_of_element_located(By.ID,'user')
3. Judge a certain element Is visible and clickable in :element_to_be_clickable(locator)
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
target = EC.element_to_be_clickable(By.ID,'user')
4. Judge a certain element Is it selected :element_to_be_selected(element) ( Usually used in drop-down list )
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
element = driver.find_element_by_class_name('selector')
EC.element_to_be_selected(element)
The following is the supporting information , For doing 【 software test 】 For our friends, it should be the most comprehensive and complete war preparation warehouse , This warehouse also accompanied me through the most difficult journey , I hope it can help you !
Last : It can be in the official account : Programmer Xiaohao ! Get a free copy of 216 Page software testing engineer interview guide document information . And the corresponding video learning tutorial is free to share !, It includes basic knowledge 、Linux necessary 、Shell、 The principles of the Internet 、Mysql database 、 Special topic of bag capturing tools 、 Interface testing tool 、 Test advanced -Python Programming 、Web automated testing 、APP automated testing 、 Interface automation testing 、 Testing advanced continuous integration 、 Test architecture development test framework 、 Performance testing 、 Safety test, etc. .
If my blog helps you 、 If you like my blog content , please “ give the thumbs-up ” “ Comment on ” “ Collection ” One button, three links ! Friends who like software testing , You can join our testing technology exchange group :779450660 There are various software testing resources and technical discussions )
边栏推荐
- 【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
- How to do Taobao full screen rotation code? Taobao rotation tmall full screen rotation code
- APEC industry +: father of the king of the ox mill, industrial Internet "king of the ox mill anti-wear faction" Valentine's Day greetings | Asia Pacific Economic media | ChinaBrand
- 2022 high voltage electrician examination and high voltage electrician reexamination examination
- Transformer structure analysis and the principle of blocks in it
- Analysis of gas fee setting under eip1559
- Goodbye 2021, how do programmers go to the top of the disdain chain?
- Operate BOM objects (key)
- Task of gradle learning
- 【c】 Digital bomb
猜你喜欢
Etcd 基于Raft的一致性保证
QT6 QML book/qt quick 3d/ Basics
Do you really know how old you are?
Software testing skills, JMeter stress testing tutorial, obtaining post request data in x-www-form-urlencoded format (24)
"Designer universe" APEC safety and health +: environmental protection Panda "xiaobaobao" Happy Valentine's Day 2022 | ChinaBrand | Asia Pacific Economic media
MDM mass data synchronization test verification
Example of peanut shell inner net penetration
Qtablewidget control of QT
2022 high voltage electrician examination and high voltage electrician reexamination examination
JVM JNI and PVM pybind11 mass data transmission and optimization
随机推荐
Do you really know how old you are?
Phpexcel import export
MySQL——SQL注入问题
2022 melting welding and thermal cutting examination materials and free melting welding and thermal cutting examination questions
强化学习-学习笔记1 | 基础概念
leetcode-540. A single element in an ordered array
Qualcomm platform WiFi -- P2P issue
2022 safety officer-c certificate examination and safety officer-c certificate registration examination
11-grom-v2-05-initialization
MySQL 8.0 data backup and recovery
"Actbert" Baidu & Sydney University of technology proposed actbert to learn the global and local video text representation, which is effective in five video text tasks
Rhcsa third day notes
Etcd raft Based Consistency assurance
9 pyqt5 qscrollarea scroll area and qscrollbar scroll bar
Introduction to golang garbage collection
Offset related concepts + drag modal box case
[secretly kill little buddy pytorch20 days -day02- example of image data modeling process]
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
Talk about daily newspaper design - how to write a daily newspaper and what is the use of a daily newspaper?
Line segment tree blue book explanation + classic example acwing 1275 Maximum number