Selenium等待方式

本文介绍了Selenium中三种等待方式:隐式等待、显式等待和一种另类的显式等待辅助方法——wait装饰器。详细阐述了每种等待机制的使用场景,包括《Python测试驱动开发》一书中提到的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

隐式等待
当使用了隐式等待执行测试的时候,如果 WebDriver没有在DOM中找到元素,将继续等待,
超出设定时间后则抛出找不到元素的异常,换句话说,当查找元素或元素并没有立即出现的时候,
隐式等待将等待一段时间再查找DOM,默认的时间是0
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
browser = webdriver.Chrome()
# 等待十秒加载不出来就会抛出异常,10秒内加载出来正常返回
browser.implicitly_wait(10)
browser.get('https://www.python.org')
try:
	input = browser.browser.find_element_by_id('id-search-field')
except NoSuchElementException as e:
	print(e)
print(input)
显式等待
指定一个等待条件,和一个最长等待时间,在等待时间内条件是否满足,
如果满足则返回,如果不满足会继续等待,直到超过设定时间就会抛出异常
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 EC

browser = webdriver.Chrome()
browser.get('https://www.python.org/')
wait = WebDriverWait(browser, 10) 
# 元素加载完后,传入定位元素
search_elem = wait.until(EC.presence_of_element_located((By.ID, 'id-search-field')))
# 元素可点击
go_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#submit')))
print(search_elem , go_btn )
  • 其他条件
EC.title_is 标题是某内容
EC.title_contains 标题包含某内容
EC.visibility_of_element_located 元素可见,传入定位元组
EC.visibility_of 可见,传入元素对象
EC.presence_of_all_elements_located 所有元素加载出后
EC.text_to_be_present_in_element 某个元素文本包含某文字
EC.text_to_be_present_in_element_value 某个元素值包含某文字
EC.frame_to_be_available_and_switch_to_it frame加载并切换
EC.invisibility_of_element_located 元素不可见
EC.staleness_of 判断一个元素是否仍在DOM,可判断页面是否已经刷新
EC.element_to_be_selected 元素可选择,传元素对象
EC.element_located_to_be_selected 元素可选择,传入定位元组
EC.EC.element_selection_state_to_be 传入元素对象以及状态,相等返回True,否则返回False
EC.element_located_selection_state_to_be 传入定位元组以及状态,相等返回True,否则返回False
EC.alert_is_present 是否出现Alert

强制等待,使用time.sleep(time_out)方法

另类显式等待辅助方法:wait装饰器

下面内容来自《Python测试驱动开发》,不错的一本书有兴趣可以阅读下

import time
from selenium import webdriver
from selenium.webdriver.common.by import By


MAX_WAIT = 5

def wait(fn): 
    def modified_fn(*args, **kwargs):
        start_time = time.time() 
        while True: 
            try: 
                return fn(*args, **kwargs)
            except (AssertionError, WebDriverException) as
                if time.time() - start_time > MAX_WAIT: 
                    raise e 
                time.sleep(0.5) 
    return modified_fn

@wait
def find_input()
	browser = webdriver.Chrome()
	browser.get('https://www.python.org')
	# 第一个参数是定位方式,第二个传入具体的参数
	input_q= browser.find_element(BY.NAME,'q')
	print(input_first)
	browser.quit()   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值