Detailed explanation of Selenium's three waiting methods (forced waiting, implicit waiting, and explicit waiting)

Preface

① When performing WEB automation work, you generally have to wait for a certain page element to be loaded before performing operations on the element. Otherwise, the automation script will throw an error that the element cannot be found, which requires us to perform certain scenarios in UI automation testing. Plus waiting time.

②The setting of waiting mode is a very important means to ensure the stable and effective operation of automated scripts.

Forced wait for sleep()

① Force waiting and set a fixed sleep time.

②Python's time package provides the sleep method sleep(); after importing the time package, you can use sleep() to sleep during the execution of the script.

code show as below:

# coding = utf-8
from time import sleep
from selenium import webdriver

# 驱动文件路径
driverfile_path = r'D:\coship\Test_Framework\drivers\chromedriver.exe'
# 启动浏览器
driver = webdriver.Chrome(executable_path=driverfile_path)
# 打开百度首页
driver.get(r'https://www.baidu.com/')
# 等待3秒
sleep(3)
driver.find_element_by_css_selector("#kw").send_keys("selenium")
# 退出
driver.quit()

Implicitly wait driver.implicitly_wait(time)

① It is equivalent to setting a global wait . When positioning an element, set a timeout for all elements .

②Set a waiting time. If the web page is loaded within this waiting time, execute the next step; otherwise, wait until the time expires before executing the next step. This also has a drawback. The program will wait for the entire page to be loaded until it times out. But sometimes the element I need has already been loaded, but there are some other elements on the page that are loading very slowly, and I still have to wait for the page. The next step cannot be performed until all loading is completed.

③Implicit waiting causes WebDriver to poll the DOM at specific intervals when searching for an Element or Elements array, if the Element or Elements array is not found immediately. The default setting is 0. Once set, this implicit wait will work throughout the lifetime of the WebDriver object instance.

# coding = utf-8
from selenium import webdriver

# 驱动文件路径
driverfile_path = r'D:\coship\Test_Framework\drivers\chromedriver.exe'
# 启动浏览器
driver = webdriver.Chrome(executable_path=driverfile_path)
# 打开百度首页
driver.get(r'https://www.baidu.com/')
driver.find_element_by_css_selector("#kw").send_keys("selenium")
driver.find_element_by_css_selector("#su").click()
# 隐式等待30秒
driver.implicitly_wait(30)
result = driver.find_elements_by_css_selector("h3.t>a")
for i in result:
    print(i.text)
# 退出
driver.quit()
现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:110685036

show wait

① Above we talked about one of the drawbacks of implicit waiting. What if I want to wait for the element I want to be loaded before executing the next step? Display waiting is used here .

② Explicit wait is a piece of code you define to wait for a certain condition to occur before continuing to execute subsequent code.

③  Within the set time, by default, the existence of the current page element will be detected every once in a while. If it cannot be detected after the set time, an exception will be thrown . The default detection frequency is 0.5s , and the default exception thrown is: NoSuchElementException  .

④ Help documentation for WebDriverWait:

>>> help(WebDriverWait)
Help on class WebDriverWait in module selenium.webdriver.support.wait:

class WebDriverWait(builtins.object)
 |  Methods defined here:
 |
 |  __init__(self, driver, timeout, poll_frequency=0.5, ignored_exceptions=None)
 |      Constructor, takes a WebDriver instance and timeout in seconds.
 |
 |      :Args:
 |       - driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
 |       - timeout - Number of seconds before timing out
 |       - poll_frequency - sleep interval between calls
 |         By default, it is 0.5 second.
 |       - ignored_exceptions - iterable structure of exception classes ignored
during calls.
 |         By default, it contains NoSuchElementException only.
 |
 |      Example:
 |       from selenium.webdriver.support.ui import WebDriverWait
 |
 |       element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_i
d("someId"))
 |
 |       is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleExcepti
on)).\
 |
 |                   until_not(lambda x: x.find_element_by_id("someId").is_displ
ayed())

Create an instance object of the WebDriverWait class: WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)

There are mainly 4 parameters:

driver: browser driver

timeout: waiting time

poll_frequency: detection interval, default 0.5s

ignored_exceptions: Exception information after timeout, NoSuchElementException is thrown by default

⑤The WebDriverWait class is used to display waiting  :

from selenium.webdriver.support.wait import WebDriverWait

Code example 1:

#encoding=utf-8
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

#获取单个页面元素对象,显示等待
#locateType查找的方法类型
#locatorExpression查找的表达式
def getElement(driver,locateType,locatorExpression):
    try:
        element=WebDriverWait(driver,5).until(lambda x: x.find_element(by=locateType, value=locatorExpression))
    except Exception, e:
        raise e

Code example 2:

# coding = utf-8
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

# 驱动文件路径
driverfile_path = r'D:\coship\Test_Framework\drivers\chromedriver.exe'
# 启动浏览器
driver = webdriver.Chrome(executable_path=driverfile_path)
# 打开百度首页
driver.get(r'https://www.baidu.com/')
driver.find_element_by_css_selector("#kw").send_keys("selenium")
driver.find_element_by_css_selector("#su").click()
# 超时时间为30秒,每0.2秒检查1次,直到class="tt"的元素出现
text = WebDriverWait(driver, 30, 0.2).until(lambda x:x.find_element_by_css_selector(".tt")).text
print(text)
# 退出
driver.quit()

Code example 3:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
driver.get('http://www.baidu.com')

element = WebDriverWait(driver, 5, 0.5).until(EC.presence_of_element_located((By.ID, "kw")))
element.send_keys('selenium')

In this example, rename expected_conditions to EC through the as keyword, and call the presence_of_element_located() method to determine whether the element exists.

Expected conditions judgment method provided by expected_conditions class

method illustrate
title_is Determine whether the title of the current page is completely equal to (==) the expected string and return a Boolean value
title_contains Determine whether the title of the current page contains the expected string and return a Boolean value
presence_of_element_located Determining whether an element has been added to the dom tree does not mean that the element must be visible.
visibility_of_element_located Determine whether an element is visible. Visible means that the element is not hidden, and the width and height of the element are not equal to 0
visibility_of It does the same thing as the above method, except that the above method needs to pass in the locator. This method can directly pass the located element.
presence_of_all_elements_located Determine whether at least 1 element exists in the dom tree. For example, if there are n elements on the page with classes all 'column-md-3', then as long as 1 element exists, this method will return True
text_to_be_present_in_element Determine whether the text in an element contains the expected string
text_to_be_present_in_element_value Determine whether the value attribute in an element contains the expected string
frame_to_be_available_and_switch_to_it Determine whether the frame can be switched in. If so, return True and switch in, otherwise return False.
invisibility_of_element_located Determine whether an element does not exist in the DOM tree or is invisible
element_to_be_clickable Determine whether an element is visible and enabled. In this case, it is called clickable.
staleness_of Wait for an element to be removed from the DOM tree. Note that this method also returns True or False.
element_to_be_selected Determine whether an element is selected, generally used in drop-down lists
element_selection_state_to_be Determine whether the selected state of an element is as expected
element_located_selection_state_to_be The function is the same as the above method, except that the above method passes in the located element, and this method passes in the locator
alert_is_present Determine whether there is an alert on the page

There are two usage scenarios for Expected Conditions:

  • Use directly in assertions
  • Used in conjunction with WebDriverWait() to dynamically wait for elements on the page to appear or disappear

Example:

#encoding:utf-8
# example of how to use https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/webdriver/support/expected_conditions.py

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By

import unittest

# dr = webdriver.PhantomJS('phantomjs')
dr = webdriver.Firefox()
# dr = webdriver.Chrome()
url = 'http://www.baidu.com'
search_text_field_id = 'kw'
dr.get(url)

class ECExample(unittest.TestCase):

  def test_title_is(self):
    ''' 判断title是否符合预期 '''
    title_is_baidu = EC.title_is(u'百度一下,你就知道')
    self.assertTrue(title_is_baidu(dr))

  def test_titile_contains(self):
    ''' 判断title是否包含预期字符 '''
    title_should_contains_baidu = EC.title_contains(u'百度')
    self.assertTrue(title_should_contains_baidu(dr))

  def test_presence_of_element_located(self):
    ''' 判断element是否出现在dom树 '''
    locator = (By.ID, search_text_field_id)
    search_text_field_should_present = EC.visibility_of_element_located(locator)

    ''' 动态等待10s,如果10s内element加载完成则继续执行下面的代码,否则抛出异常 '''
    WebDriverWait(dr, 10).until(EC.presence_of_element_located(locator))
    WebDriverWait(dr, 10).until(EC.visibility_of_element_located(locator))

    self.assertTrue(search_text_field_should_present(dr))

  def test_visibility_of(self):
    search_text_field = dr.find_element_by_id(search_text_field_id)
    search_text_field_should_visible = EC.visibility_of(search_text_field)
    self.assertTrue(search_text_field_should_visible('yes'))

  def test_text_to_be_present_in_element(self):
    text_should_present = EC.text_to_be_present_in_element((By.NAME, 'tj_trhao123'), 'hao123')
    self.assertTrue(text_should_present(dr))


  @classmethod
  def tearDownClass(kls):
    print 'after all test'
    dr.quit()
    print 'quit dr'

if __name__ == '__main__':
  unittest.main()

Take title_is as an example:

class title_is(object):
    """An expectation for checking the title of a page.
    title is the expected title, which must be an exact match
    returns True if the title matches, false otherwise."""
    def __init__(self, title):
        self.title = title

    def __call__(self, driver):
        return self.title == driver.title

You can see that title_is is actually a class, and its __call__ method is defined to return a bool value. Therefore, the general usage is:

# 实例化
the_instance = title_is('expected')
# 直接在实例上调用__call__
the_instance(dr) #return True or False

Detailed explanation of webDriverWait()

WebDriverWait(self,driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None).until(self, method, message=)

or:

WebDriverWait(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None).until_not(self,method, message=)

① self: The function itself does not require input when actually used.

② driver: webdriver driver, such as (IE, FireFox, chrome, safari, etc.).

③ timeout: timeout time, the default unit is seconds poll_frequency, the interval of sleep time (step size), the default is 0.5 seconds , that is, the frequency of detecting whether the element exists.

④ ignored_exceptions: Exception information after timeout. By default, NoSuchElementException exception information is thrown. You can define ignored exception information.

⑤ WebDriverWait is generally used in conjunction with until or until_not.

⑥ until(method, message="): Call the driver provided by this method as a parameter until the return value is not False.

⑦ until_not(method, message="): Call the driver provided by this method as a parameter until the return value is False.

Practical application

In automated testing, many times you will wait for a certain element on the page to appear before proceeding to the next operation, or the list will display loading, and the next operation will not proceed until the loading is completed, but the time is uncertain, as shown in the following figure:

code show as below:

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import selenium.webdriver.support.expected_conditions as EC
import selenium.webdriver.support.ui as ui



# 一直等待某元素可见,默认超时10秒
def is_visible(locator, timeout=10):
    try:
        ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.XPATH, locator)))
        return True
    except TimeoutException:
        return False

# 一直等待某个元素消失,默认超时10秒
def is_not_visible(locator, timeout=10):
    try:
        ui.WebDriverWait(driver, timeout).until_not(EC.visibility_of_element_located((By.XPATH, locator)))
        return True
    except TimeoutException:
        return False

# 调用
is_not_visible('//input[@input="search-error"]') 

Finally, I would like to thank everyone who read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software testing interview applet

A software test question bank that has been used by millions of people! ! ! Who is who knows! ! ! The most comprehensive interview test mini program on the Internet, you can use your mobile phone to answer questions, take the subway, bus, and roll it up!

Covers the following interview question sections:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. Web, app, interface automation, 7. Performance testing, 8. Programming basics, 9. HR interview questions, 10. Open test questions, 11. Security testing, 12. Computer basics

Information acquisition method:

Guess you like

Origin blog.csdn.net/myh919/article/details/132690596