selenium元素等待的三种方法

1.强制等待sleep()

使用方法:sleep(X),等待X秒后,进行下一步操作。

使用最简单的一种办法就是强制等待sleep(X),强制让浏览器等待X秒,不管当前操作是否完成,是否可以进行下一步操作,都必须等X秒的时间。

缺点:不能准确把握需要等待的时间(有时操作还未完成,等待就结束了,导致报错;有时操作已经完成了,但等待时间还没有到,浪费时间)

优点:使用简单,可以在调试时使用

2.隐式等待implicitly_wait()

使用方法:(WebDriver类下的)implicitly_wait(X),在X时间内,页面加载完成,进行下一步操作

说明:首先Implicit Waits默认是等待时间是0,同时隐性等待是对driver起作用,所以只要设置一次即可,比强制等待更智能

from selenium import webdriver

from selenium.common.exceptions import NoSuchElementException

import time

driver=webdriver.Firefox()

driver.get("https://www.baidu.com")

driver.implicitly_wait(5) #隐式等待时间设置5秒

#检测搜索框是都存在

try:

    print(time.ctime()) #打印当前时间,精确到秒

    driver.find_element_by_id("kw").send_keys("python") #id 定位,最多等待5秒

    driver.find_element_by_css_selector("#su").click() #最多等待5秒,隐式等待对这里的都起到作用,直接执行完

#如果出现了异常,则打印出来

except NoSuchElementException as mss:

    print(mss)

finally:

    print(time.ctime())

time.sleep(6)

driver.quit()

3.显示等待 WebDriverWait()

需要先导入from selenium.webdriver.support.wait import WebDriverWait

WebDriverWait()会配合until()和until_not()方法一起使用

使用方法:

WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None).until(要执行的方法)

driver:浏览器实例

timeout:超时时间,默认已秒为单位

poll_frequency:检测时间间隔,默认0.5秒

ignored_exceptions:报错信息,默认抛出NoSuchElementException

WebDriverWait 类 :until() 和 until_not()

until():可以传两个参数,第一个参数是判断条件,直到第一个参数返回True。第二个参数可以写文字说明。直到条件成立返回为真,等待结束。如果超时,抛出TimeoutException,将message传入异常

until_not():可以传两个参数,第一个参数是判断条件,直到第二个参数返回 False。第二个参数可以写文字说明。直到条件不成立返回为真,是当某元素消失或什么条件不成立则继续执行,等待结束。如果超时,抛出TimeoutException,将message传入异常

以下几个条件验证:

3.1验证 title

title_is :验证传入的参数 title 是否等于 driver.title

title_contains :验证传入的参数 title 是否包含于 driver.title

3.2验证元素是否出现,传入的参数都是元组类型的 locator,如(By.ID,'kw')

presence_of_element_located :只要一个符合条件的元素加载出来就通过

presence_of_all_elements_located :必须所有符合条件的元素都加载出来才行

3.3验证元素是否可见:

visibility_of_element_located :传入的参数是元组类型的 locator

invisibility_of_element_located :传入的参数是元组类型的 locator

visibility_of :传入 WebElement,第一个和第三个是一样的

3.4判断某段文本是否出现在某元素中

text_to_be_present_in_element :判断元素的 text

text_to_be_present_in_element_value :判断元素的 value

3.5判断 frame 是否可切入,可传入 locator 元组或者直接传入定位方式:id、name、index 或 WebElement

frame_to_be_available_and_switch_to_it

3.6判断是否有 alert 出现

alert_is_present

3.7判断元素是否可点击,传入 locator

element_to_be_clickable

3.8判断元素是否被选中

element_to_be_selected :传入 WebElement 对象

element_located_to_be_selected :传入 locator 元组

element_selection_state_to_be:传入 WebElement 对象以及状态,相等返回 True,否则返回 False

element_located_selection_state_to_be:传入 locator 以及状态,相等返回 True,否则返回 False

3.9判断一个元素是否仍在 DOM 中,传入 WebElement 对象,可以判断页面是都刷新

staleness_of

3.10WebElement 自带方法

is_displayed() :判断元素是否展示出来

is_enabled() :判断元素是否可操作

原文地址:https://www.cnblogs.com/renshengruxi/p/12553480.html