selenium 设置元素等待
webdriver 有2种等待方式:显式等待和隐式等待
显式等待
定义:使webdriver等待某个条件成立时继续执行,否则达到最大时长时抛出异常
WebdriverWait类是由WebDriver 提供的等待方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则会抛出异常。
格式如下:
WebDriverWait(driver,timeout,poll_frequency = 0.5,ignored_exceptions = None)
- driver:浏览器驱动
- timeout:最长超时时间默认以秒为单位
- poll_frequency:检测的间隔时间,默认为0.5S
- ignored_exceptions:超时后的异常信息,默认情况下抛出NoSuchElementException异常
WebDriverWait()一般由until()或until_not()方法配合使用,下面是until()和until_not()方法的说明。
- until(method,message = ''+3)
调用该方法提供的驱动程序为一个参数,知道返回值为False
在以下示例中,通过as关键字将excepected_conditions重命名为EC,并调用presence_of_element_located()方法判断元素是否存在。
1 #-*-coding:utf-8 -*- 2 print("hello,world") 3 from selenium import webdriver 4 from selnium.webdriver.common.by import By 5 from selnium.webdriver.support.ui import webdriverWait 6 from selenium.webdriver.support import expected_conditions as EC 7 8 driver = webdriver.Firefox() 9 driver.get('http://www.baidu.com') 10 11 element = webdriverWait(driver,5,0.5).until( 12 EC.presence_of_element_located((By.ID,'kw')) 13 ) 14 element.send_keys('selenium') 15 driver.quit()
隐式等待
WebDriver提供了implicitly_wait()方法来实现隐式等待,默认设置为0,用法相对简单。
1 #隐式等待 2 from selenium import webdriver 3 from selenium.common.exceptions import NoSuchElementException 4 from time import ctime 5 6 driver = webdriver.Firefox() 7 8 #设置隐式等待为10s 9 driver.implicitly_wait(10) 10 driver.get("http://www.baidu.com") 11 try: 12 print(ctime()) 13 driver.find_element_by_id('kw22').send_keys('selenium') 14 except NoSuchElementException as e: 15 print(e) 16 17 finally: 18 print(ctime()) 19 driver.quit()
implicitly_wait()默认参数的单位为秒,延时等待是在设定好的时间内,不断进行元素定位(轮询),定位到了就继续执行,定位不到则在设定的时间后抛出异常。
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现