云和教育:云和数据集团旗下高端ICT职业教育品牌
  • 国家级全民数字素养与技能培训基地
  • 河南省第一批产教融合型企业建设培育单位
  • 郑州市数字技能人才(码农)培养评价联盟

自动化测试小技巧之Selenium的等待实现方式

  • 作者:云和教育
  • 日期:2023-10-10
  • 浏览:194次

9a44c0a054a8c4f8168b7c1167045ef.png

页面还没加载出来就对页面上的元素进行操作,就会出现:因为加载元素延时造成的脚本失败,我们可以通过设置等待时间来提升自动化脚本的稳定性。

WebDriver 提供了3种类型的等待:显式等待、隐式等待、休眠

² 显式等待是针对某一个元素进行相关等待判定;

² 隐式等待不针对某一个元素进行等待,全局元素等待;

² sleep 休眠方法。

1.方式1:显式等待

WebDriverWait 类由 WebDriver 提供的等待方法。在设置时间内,默认每个一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则抛出异常

² WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None)

² n Driver 浏览器驱动

² n Timeout最长超时时间,默认以秒为单位

² n poll_frequency 检测的间隔时间,默认为 0.5 秒

² n ignored_exceptions 超 时 后 的 异 常 信 息 , 默 认 情 况 下 抛 出

² NoSuchElementException 异常

² WebDriverWait 一般由 until()和 until_not()方法配合使用

² n until(method,message=’’) 调用该方法提供的驱动程序作为一个参数,知道返回值为 Ture

² n until_not(method,message=’’ 调用该方法提供的驱动程序作为一个参数,知道返回值为 False

2.代码实现

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
# as expected_conditions重命名为EC
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

指定浏览器位置
chrome_location = 
r'D:\software\Win_x64_1135105_chrome-win\chrome-win\chrome.exe'
options = webdriver.ChromeOptions()
options.binary_location = chrome_location

driver = webdriver.Chrome(options=options)
driver.get(r'https://www.baidu.com/')

driver.find_element(By.CSS_SELECTOR, '#kw').send_keys('selenium')
sleep(
3)
显式等待 30 判断搜索按钮是否存在
element = WebDriverWait(driver, 300.5).until(EC.presence_of_element_located((By.ID, 'su'))
element.click()
sleep(
3)
driver.quit()

3.方式2:隐式等待

implicitly_wait() 默认参数的单位为秒。隐性等待设置了一个时间,在一段时间内网页是否加载完成,如果完成了,就进行下一步;在设置的时间内没有加载完成,则会报超时加载。

4.代码实现

# coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from time import sleep, ctime
指定浏览器位置
chrome_location = 
r'D:\software\Win_x64_1135105_chrome-win\chrome-win\chrome.exe'
options = webdriver.ChromeOptions()
options.binary_location = chrome_location
driver = webdriver.Chrome(
options=options)
隐式等待 30 
driver.implicitly_wait(30)
driver.get(
r'https://www.baidu.com')
检测搜索框是否存在
try:
   driver.find_element(By.CSS_SELECTOR, 
'#kw').send_keys('selenium')
   driver.find_element(By.CSS_SELECTOR, 
'#su').click
except NoSuchElementException as msg:
   
print(msg)
sleep(
3)
driver.quit()

5.方式3:sleep 休眠

sleep()方法有 Python 的 time 模块提供。在脚本调试过程中,希望脚本再执行到某一位置时做固定时间的休眠,则可以使用。

sleep()默认参数以秒为单位,如果设置时长小于 1 秒,则用小数表示。