显式等待&隐式等待

一、为什么等待?
由于浏览器加载及渲染的速度不一致,导致无法很好的定位给元素,所以需要智能化的等待元素
二、两个等待的区别:显式等待针对某一个特定元素,隐式等待针对全局元素
三、显示等待
1、相关模块
webDiverWait 显示等待针对元素比用
Expected conditions预期条件类(里面包含方法可以调用,用于显示等待)
NoSuchElementException用于隐式等待抛出异常
By用于元素定位
2、WebDiverWait模块:
在这里插入图片描述
1)driver:传入webdriver实例,即浏览器驱动
2)Timeout:超时时间,等待的最长时间(同时要考虑隐性等待时间)
3)Poll_frequency:调用until或until_not中的方法的间隔时间,默认是0.5秒
4)ignored_exceptions:忽略的异常,如果在调用until或until_not中抛出这个元组的异常则不中断代码,继续等待,如果抛出的是元组外的,则中断代码,抛出异常,默认只有NoSuchElementException
5)Until:当元素出现或什么条件成立则继续执行;
Until_not是当什么元素消失或条件不成立则继续执行
6)调用方法:WebDiverWait(driver,超时时长,间隔时间).until(判断条件)
举例:WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,‘su’)))
3、Expected conditions预期条件类:是selenium一个模块,用于判断
1)title_is/title_contains:判断传入的参数是否等于或包含driver.title
2)Presence_of_element_located/presence_of_all_elements_located:判断元素是否出现,前者是验证一个,后者是全部
3)其余方法可通过按CTRL点击对应模块查看

在这里插入图片描述
4、显示等待判断搜索按钮是否出现代码:
#!/usr/bin/env python

encoding: utf-8

“”"
@version: ??
@author: oxl
@license: Apache Licence
@file: excirse.py
@time:2019/12/1 14:45
“”"
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from time import sleep
driver=webdriver.Chrome()
driver.get(‘http://www.baidu.com’)
sleep(2)

driver.find_element_by_css_selector("#kw").send_keys(“selenium”)
element=WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,‘su’)))#搜索按钮的id,当前页面中5秒内每0.5检测对应元素
element.click()
5、隐式等待定义方法:driver.implicitly_wait(等待时间)
6、隐式等待实现代码:
#!/usr/bin/env python

encoding: utf-8

“”"
@version: ??
@author: oxl
@license: Apache Licence
@file: excirse.py
@time:2019/12/1 14:45
“”"
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException as EC
from selenium.webdriver.common.by import By
from time import sleep
driver=webdriver.Chrome()
driver.get(‘http://www.baidu.com’)
sleep(2)

driver.find_element_by_css_selector("#kw").send_keys(“selenium”)
driver.implicitly_wait(5)
try:
driver.find_element_by_css_selector("#suu").click()
except EC as msg:
print(msg)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值