selenium 3种等待方式

编程入门 行业动态 更新时间:2024-10-18 21:23:05

selenium 3种等待<a href=https://www.elefans.com/category/jswz/34/1771414.html style=方式"/>

selenium 3种等待方式

三种等待方式

①强制等待
强制等待是使线程休眠一定时间。强制等待一般在隐式等待和显式等待都不起作用时使用。示例代码如下:

time.sleep(3)

②隐式等待
隐式等待的作用是全局的,是作用于整个 session 的生命周期,也就是说只要设置一次隐式等待,后面就不需要设置。如果再次设置隐式等待,那么后一次的会覆盖前一次的效果。

当在 DOM 结构中查找元素,且元素处于不能立即交互的状态时,将会触发隐式等待。

driver.implicitly_wait(30)

③显式等待
显式等待是在代码中定义等待条件,触发该条件后再执行后续代码,就能够根据判断条件进行等待。程序每隔一段时间进行条件判断,如果条件成立,则执行下一步,否则继续等待,直到超过设置的最长时间。核心用法如下:

# 导入显示等待
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
...
# 设置10秒的最大等待时间,等待 (By.TAG_NAME, "title") 这个元素点击
WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.TAG_NAME, "title"))
)
...

一个案例

#导入依赖
import time
from selenium import webdriver
from selenium.webdrivermon.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWaitclass TestHogwarts():
def setup(self):self.driver = webdriver.Chrome()self.driver.get('/')
#加入隐式等待self.driver.implicitly_wait(5)def teardown(self):
#强制等待time.sleep(10)self.driver.quit()def test_hogwarts(self):
#元素定位,这里的category_name是一个元组。category_name = (By.LINK_TEXT, "开源项目")
# 加入显式等待WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable(category_name))
# 点击开源项目self.driver.find_element(*category_name).click()

更多推荐

selenium 3种等待方式

本文发布于:2023-12-04 16:01:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1661462.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   selenium

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!