【selenium】三种等待方式
创始人
2024-02-05 06:46:15
0次

selenium 三种等待方式演示。

  • 强制等待
  • 隐式等待
  • 显式等待

强制等待

import time
# 整个程序强制等待 3 秒
time.sleep(3)

隐式等待

设置一个全局的等待时间,以隐式等待找到元素或完成命令。每个会话只需要调用一次此方法。

# Amount of time to wait (in seconds)
driver.implicitly_wait(3)

显式等待

定义等待条件,满足条件才继续向下执行,否则继续等待,超时后抛出异常。更加灵活的等待方式,项目中最常用的等待方式。

显示等待类 WebDriverWait 初始化接收四个参数:

  • driver:自动化驱动
  • timeout:总等待时间
  • poll_frequency:轮询间隔时间
  • ignored_exceptions:忽略预期的异常类型

两个判断条件:

def until(self, method, message=''):"""调用传入的方法作为参数,直到返回值不是 False"""def until_not(self, method, message=''):"""调用传入的方法作为参数,直到返回值为 False"""

示例

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import StaleElementReferenceExceptionclass TestWait:def setup_class(self):self.driver = webdriver.Chrome()self.driver.get("https://www.baidu.com")self.driver.implicitly_wait(5)  # 隐式等待def teardown_class(self):self.driver.quit()def test_sleep(self):""" 强制等待无论元素是否出现都强制等待"""ele = self.driver.find_element(By.ID, "kw")time.sleep(10)ele.send_keys("hello")def test_implicitly_wait(self):""" 隐式等待设置在初始化 driver 处,元素 5 秒不出现才报错"""ele = self.driver.find_element(By.ID, "test")  # 随便设置个元素ele.click()def test_webdriver_wait_by_def(self):""" 显式等待自定义方法编写条件"""def wait(x):  # 参数为必传项hot_search_items = self.driver.find_elements(By.XPATH, '//*[@class="title-content-title"]')return len(hot_search_items) == 6# 等待百度热搜出现 6 条则继续向下执行,否则最大等待时间为 10 秒,0.5 秒轮询一次WebDriverWait(self.driver, 10).until(wait)def test_webdriver_wait_by_ec(self):""" 显式等待使用预置的等待条件库 expected_conditions"""# 等待热搜词可点击才继续向下执行,否则最大等待时间为 10 秒,每秒轮询一次WebDriverWait(self.driver, 1, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, '//*[@class="title-content-title"]')))def test_webdriver_wait_until_not(self):""" 显式等待每 5 秒看一次该元素是否展示,如果不展示则用例直接通过"""WebDriverWait(self.driver, 5, 10).until_not(expected_conditions.element_to_be_clickable((By.XPATH, 'hello')))def test_webdriver_wait_ignored_exceptions(self):""" 显式等待忽略某种预期内的异常,继续轮询等待"""WebDriverWait(self.driver, 1, 5, StaleElementReferenceException).until(# 可以在 WebDriverWait 初始化时添加忽略异常, 如上当页面元素未更新时也不会报错,继续轮询# 默认为 NoSuchElementExceptionexpected_conditions.element_to_be_clickable((By.ID, "test")))
expected_conditions API
"""* Canned "Expected Conditions" which are generally useful within webdriver* tests.
"""class title_is(object):"""标题完全匹配,返回 bool"""
class title_contains(object): """标题包含匹配,区分大小写"""class url_contains(object):"""url 片段匹配,区分大小写,返回 bool"""
class url_matches(object):"""url 正则匹配,返回 bool"""
class url_to_be(object):"""url 精确匹配,返回 bool"""
class url_changes(object):"""url 不匹配则为真,否则为假"""class presence_of_element_located(object):"""页面元素是否存在,并不一定可见,接收一个 locator"""
class visibility_of_element_located(object):"""元素是否在页面中必须展示,且高度宽度大于0,接收一个 locator"""
class visibility_of(object):"""元素是否可见,可见则返回元素,否则返回 false"""
class presence_of_all_elements_located(object):"""查找一组元素,无论是否在页面可见"""
class visibility_of_any_elements_located(object):"""查找一组元素,返回该元素中所有在页面可见的元素"""
class visibility_of_all_elements_located(object):"""查找一组元素,该元素都页面中可见"""class text_to_be_present_in_element(object):"""检查指定文本是否存在于元素的文本当中"""
class text_to_be_present_in_element_value(object):"""检查指定文本是否存在于元素的属性值当中"""class frame_to_be_available_and_switch_to_it(object):"""检查是否可以切换到指定 locator 的 frame 当中"""class invisibility_of_element_located(object):""" 元素在页面中不可见或不存在 """
class element_to_be_clickable(object):"""元素是否可被点击"""
class staleness_of(object):"""元素是否停止加载,依然加载返回 false,否则为 true"""
class element_to_be_selected(object):"""获取元素对象的 is_selected 属性"""
class element_located_to_be_selected(object):"""通过 locator 定位元素,获取该元素的 is_selected 属性"""
class element_selection_state_to_be(object):"""当前元素是否为选中状态"""
class element_located_selection_state_to_be(object):"""当前元素是否可被选中"""class number_of_windows_to_be(object):"""判断当前浏览器窗口数量"""
class new_window_is_opened(object):"""检查是否打开了一个新窗口"""
class alert_is_present(object):"""alert 弹窗是否chu'xian"""

显式等待 + 窗口切换官方示例

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ECwith webdriver.Chrome() as driver:# Open URLdriver.get("https://www.baidu.com")# Setup wait for laterwait = WebDriverWait(driver, 10)# Store the ID of the original windoworiginal_window = driver.current_window_handle# Check we don't have other windows open alreadyassert len(driver.window_handles) == 1# Click the link which opens in a new windowdriver.find_element(By.LINK_TEXT, "新闻").click()# Wait for the new window or tabwait.until(EC.number_of_windows_to_be(2))# Loop through until we find a new window handlefor window_handle in driver.window_handles:if window_handle != original_window:driver.switch_to.window(window_handle)break# Wait for the new tab to finish loading contentwait.until(EC.title_is("百度新闻——海量中文资讯平台"))

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...