元素等待(显式...)

来源:互联网 发布:js中连接符后怎么使用 编辑:程序博客网 时间:2024/05/16 19:55

显式等待(等待元素出现,否则超时抛出异常:TimeoutException):

#coding=utf-8from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Firefox()driver.get("http://www.baidu.com")element = WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,"kw")))element.send_keys('selenium')driver.quit()

WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)

driver - WebDriver 的驱动程序(Ie, Firefox,Chrome 等)

timeout - 最长超时时间,默认以秒为单位

poll_frequency - 休眠时间的间隔(步长)时间,默认为 0.5 秒

ignored_exceptions - 超时后的异常信息,默认情况下抛 NoSuchElementException 异常。

WebDriverWait()一般由 until()(或 until_not())方法配合使用,下面是 until()和 until_not()方法的说明。

until(method, message=’ ’)调用该方法提供的驱动程序作为一个参数,直到返回值为 Ture。

until_not(method, message=’ ’)调用该方法提供的驱动程序作为一个参数,直到返回值为 False。

expected_conditions 类提供一些预期条件的实现。

title_is 用于判断标题是否 xx。

title_contains 用于判断标题是否包含 xx 信息。

presence_of_element_located 元素是否存在。

visibility_of_element_located 元素是否可见。

visibility_of 是否可见

presence_of_all_elements_located 判断一组元素的是否存在

text_to_be_present_in_element 判断元素是否有 xx 文本信息

text_to_be_present_in_element_value 判断元素值是否有 xx 文本信息

frame_to_be_available_and_switch_to_it 表单是否可用,并切换到该表单。

invisibility_of_element_located 判断元素是否隐藏

element_to_be_clickable 判断元素是否点击,它处于可见和启动状态

staleness_of 等到一个元素不再是依附于 DOM。

element_to_be_selected 被选中的元素。

element_located_to_be_selected 一个期望的元素位于被选中。

element_selection_state_to_be 一个期望检查如果给定的元素被选中。

element_located_selection_state_to_be 期望找到一个元素并检查是否选择状态

alert_is_present 预期一个警告信息

隐式等待(WebDriver 提供implicitly_wait()方法来实现,默认时间为 0:相当于全局变量。等待元素最长时间,若超过未检测到,则抛NoSuchElementException异常)

#coding=utf-8from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitdriver = webdriver.Firefox()driver.implicitly_wait(10)driver.get("http://www.baidu.com")input_ = driver.find_element_by_id("kw22")input_.send_keys('selenium')driver.quit()


sleep休眠(做固定时间的休眠,sleep()由 Python 的 time 模块提供)

#coding=utf-8from selenium import webdriverfrom time import sleepdriver = webdriver.Firefox()driver.get("http://www.baidu.com")sleep(2)driver.find_element_by_id("kw").send_keys("webdriver")driver.find_element_by_id("su").click()sleep(3)driver.quit()



                                             
0 0