1.强制等待
import time
time.sleep(3) # 强制等待3秒
2.隐性等待
隐形等待是设置了一个最长等待时间,如果在规定时间内网页加载完成,则执行下一步,否则一直等到时间截止,然后执行下一步。
注意这里有一个坑,就是程序会一直等待整个页面加载完成,也就是一般情况下你看到浏览器标签栏那个小圈不再转,才会执行下一步。js一般都是放在body的最后进行加载,实际页面上的元素都已经加载完成,但是还要等待js加载完毕才会执行下一步操作。
需要特别说明的是:隐性等待对整个driver的周期都起作用,所以只要设置一次即可,我曾看到有人把隐性等待当成了sleep在用,走哪儿都来一下…
driver.implicitly_wait(30) # 隐性等待30秒
3. 显性等待
使用WebDriverWait类,配合该类的until()和until_not()方法使用。
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as Ec
driver = webdriver.Chrome()
driver.implicitly_wait(10) # 最长等待时间10秒,隐性等待和显性等待可以同时用,但要注意:等待的最长时间取两者之中的大者
driver.get("http://www.baidu.com/")
e = WebDriverWait(driver, 30).until(Ec.presence_of_element_located(('id', 'kw'))) #等待id为kw的元素出现后,再执行下一步操作,最长等待时间30秒
e.send_keys(111)
4.WebDriverWait类说明
__init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None)
其中
driver:WebDriver的实例 (Ie, Firefox, Chrome or Remote);
timeout:超时时间,即最大的等待时间;
poll_frequency:until或until_not中,执行method的间隔时间,默认为0.5秒;
ignored_exceptions:忽略的异常。如果在调用until或until_not的过程中抛出这个元组中的异常,则不中断代码,继续等待;如果抛出的是这个元组外的异常,则中断代码,抛出异常。默认只有NoSuchElementException。
until(method, message='')
method:在等待期间,每隔一段时间(__init__中的poll_frequency)调用这个传入的方法,直到返回值不是False。
message:等待超时后,返回的异常信息。
until_not(method, message='')
method:在等待期间,每隔一段时间(__init__中的poll_frequency)调用这个传入的方法,直到返回值为False。
message:等待超时后,返回的异常信息。
5.expected_conditions
until或until_not传入的method可以用selenium提供的 expected_conditions 模块中的各种条件,也可以用WebElement的 is_displayed() 、is_enabled()、is_selected() 方法,或者用自己封装的方法都可以。
selenium.webdriver.support.expected_conditions模块中,比较常用的为presence_of_element_located,对每个元素进行操作时,都需要先调用presence_of_element_located确定元素存在,再进行操作
visibility_of_element_located与presence_of_element_located区别
visibility表示元素在页面上是否可见,可见一定存在
presence表示元素在页面上是否存在,存在不一定可见,即有的元素加载出来了,但是页面上可能看不到
class visibility_of_element_located(object):
""" An expectation for checking that an element is present on the DOM of a
page and visible. Visibility means that the element is not only displayed
but also has a height and width that is greater than 0.
locator - used to find the element
returns the WebElement once it is located and visible
"""
class presence_of_element_located(object):
""" An expectation for checking that an element is present on the DOM
of a page. This does not necessarily mean that the element is visible.
locator - used to find the element
returns the WebElement once it is located
"""
参考链接
博客介绍了Selenium的三种等待方式。强制等待未详细说明;隐性等待设置最长等待时间,等页面加载完成执行下一步,对整个driver周期起作用;显性等待使用WebDriverWait类配合方法。还介绍了WebDriverWait类及expected_conditions模块常用条件。

1298

被折叠的 条评论
为什么被折叠?



