selenium等待处理

一,强制等待

import time
time.sleep(1) #强制等待一秒

二,隐式等待

from selenium import webdriver

driver = webdriver.Chrome()
driver.implicitly_wait(30)  # 隐性等待,最长等30秒
driver.get('http://www.baidu.com')
driver.quit()

三,显式等待(重点)

WebDriverWait,配合该类的until()和until_not()方法,就能够根据判断条件而进行灵活地等待了。它主要的意思就是:程序每隔xx秒看一眼,如果条件成立了,则执行下一步,否则继续等待,直到超过设置的最长时间,然后抛出TimeoutException。

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
WebDriverWait(driver, 超时时长, 调用频率, 忽略异常).until(可执行方法, 超时时返回的信息)

lacator 为元组eg.

(By.ID,"eWebEditor")

可执行方法为 你可以用selenium提供的  expected_conditions  模块中的各种条件,也可以用WebElement的  is_displayed()is_enabled()is_selected()  方法,或者用自己封装的方法.


WebDriverWait API如下


expected_conditions API如下


以下两个条件类验证title,验证传入的参数title是否等于或包含于driver.title 
title_is 
title_contains

以下两个条件验证元素是否出现,传入的参数都是元组类型的locator,如(By.ID, ‘kw’) 
顾名思义,一个只要一个符合条件的元素加载出来就通过;另一个必须所有符合条件的元素都加载出来才行 
presence_of_element_located 
presence_of_all_elements_located

以下三个条件验证元素是否可见,前两个传入参数是元组类型的locator,第三个传入WebElement 
第一个和第三个其实质是一样的 
visibility_of_element_located 
invisibility_of_element_located 
visibility_of

以下两个条件判断某段文本是否出现在某元素中,一个判断元素的text,一个判断元素的value 
text_to_be_present_in_element 
text_to_be_present_in_element_value

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

以下条件判断是否有alert出现 
alert_is_present

以下条件判断元素是否可点击,传入locator 
element_to_be_clickable

以下四个条件判断元素是否被选中,第一个条件传入WebElement对象,第二个传入locator元组 
第三个传入WebElement对象以及状态,相等返回True,否则返回False 
第四个传入locator以及状态,相等返回True,否则返回False 
element_to_be_selected 
element_located_to_be_selected 
element_selection_state_to_be 
element_located_selection_state_to_be

最后一个条件判断一个元素是否仍在DOM中,传入WebElement对象,可以判断页面是否刷新了 
staleness_of

上面是所有17个condition,与until、until_not组合能够实现很多判断,如果能自己灵活封装,将会大大提高脚本的稳定性。


  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值