基础复习:元素等待

 元素等待类型

1. 显式等待
2. 隐式等待

 1.显式等待

概念:使WebDriver等待指定元素条件成立时继续执行,否则在达到最大时长时抛出超时异常(TimeoutException)

提示:
    1). 在WebDriver中把显式等待的相关方法封装在WebDriverWait类中
    2). 等待是判定条件成立时,那如何判断条件成立?相关判断的方法封装在expected_conditions类中

实现

1. 导包 等待类         --> from selenium.webdriver.support.wait import WebDriverWait
2. 导包 判断条件     --> from selenium.webdriver.support import expected_conditions as EC
                        (将expected_conditions 通过as关键字起个别名:EC)
3. WebDriverWait(driver, timeout, poll_frequency=0.5)
        1). driver:浏览器对象
        2). timeout:超时的时长,单位:秒
        3). poll_frequency:检测间隔时间,默认为0.5秒
4. 调用方法 until(method):直到..时
        1). method:调用EC.presence_of_element_located(element)
                    element:调用By类方法进行定位

示例

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
url = "https://www.baidu.com"
driver = webdriver.Firefox()
driver.get(url)
element = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID, 'kw')))
element.send_keys("admin")

2.隐式等待

说明:等待元素加载指定的时长,超出抛出NoSuchElementException异常,实际工作中,一般都使用隐式等待;

显式与隐式区别:
    1. 作用域:显式等待为单个元素有效,隐式为全局元素
    2. 方法:显式等待方法封装在WebDriverWait类中,而隐式等待则直接通过浏览器实例化对象调用

 隐式等待调用方法

方法:implicitly_wait(timeout)
      (timeout:为等待最大时长,单位:秒)

调用:driver.implicitly_wait(10)
      (driver:为浏览器实例化对象名称)

隐式等待执行-说明

如果定位某一元素定位失败,那么就会触发隐式等待有效时长,如果在指定时长内加载完毕,则继续执行,否则
抛出NoSuchElementException异常,如果元素在第一次就定位到则不会触发隐式等待时长;

expected_conditions :
  • title_is:判断当前页面的title是否完全等于(==)预期字符串,返回是布尔值
  • title_contains 判断当前页面的title是否包含预期字符串,返回布尔值
  • presence_of_element_located:判断某个元素是否被加到了dom树里,并不代表该元素一定可见
  • visibility_of_element_located : 判断某个元素是否可见. 可见代表元素非隐藏,并且元素的宽和高都不等于0
  • visibility_of :跟上面的方法做一样的事情,只是上面的方法要传入locator,这个方法直接传定位到的element就好了
  • presence_of_all_elements_located : 判断是否至少有1个元素存在于dom树中。举个例子,如果页面上有n个元素的class都是'column-md-3',那么只要有1个元素存在,这个方法就返回True
  • text_to_be_present_in_element : 判断某个元素中的text是否 包含 了预期的字符串

实际操作】可封装相应方法使用:
class Base():

def __init__(self, driver):
self.driver = driver

# 查找元素
def base_find_ele(self, loc, timeout=30, poll=0.5):
return WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll).until(lambda x: x.find_element(*loc))
 
posted @ 2021-11-16 22:35  zxy_ang  阅读(105)  评论(0)    收藏  举报