python自动化8 等待处理
发布日期:2023-05-26 14:15:28 浏览次数:8 分类:技术文章

本文共 1908 字,大约阅读时间需要 6 分钟。

为了保证脚本的稳定性,有时候需要引入等待时间,等待页面加载元素后再进行操作,selenium提供三种等待时间设置方式。

sleep():固定休眠时间设置

python的time包里提供了休眠方法sleep,导入包后就能使用:

sleep()方法以秒为单位,如果超时设置小于1秒,可以使用小数
import time
time.sleep(0.5)

implicitlyWait:隐式等待

implicitlyWait()方法比sleep0方法智能sleep()方法只能在一个固定的时间等待,而implicitlyWait()可以在一个时间范围内等待称为隐式等待

driver.implicitly_wait(100)
element=driverfind_element_by_css_selector( “div.red box”)备注: 设置等待时间100s,页面上的元素5s后出现,只等待5s。不会等待100秒。
机制:
智能等待:在一个时间段内的等待
1.全局设置:只要在find_elements就会等待范围内等待;
2.每隔500ms在界面进行一次检查,如果检查到了就不等待,如果在设置时间内没检查到则报错。

from selenium.webdriver.support.ui import WebDriverWaitclass WebDriver:    def __init__(self,driver_path=config_u.get_driver_path):        path = Service(driver_path)        self.driver = webdriver.Firefox(service=path)        self.mouse = ActionChains(self.driver)           	def find_element_xpath(self,xpath_path,key_word):     	self.driver.find_element(By.XPATH,xpath_path).send_keys(key_word)    def element_implicitly(self,sec):        #隐式等待        self.driver.implicitly_wait(sec)        pass

WebDriverWait():显示等待

语法格式如下:

WebDriverWait(driver,timeout,poll_frequency=0.5,ignore_exceptions=None)
driver: WebDriver的驱动程序(IE火狐,谷歌或远程);
timeout: 最长超时时间,默认以秒为单位;
poll_frequency: 休眠时间的间隔(步长)时间,默认为0.5秒(即每500毫秒扫描一次页面);
ignore_exceptions:超时后的异常信息,默认情况下抛NoSuchElementException异常;
在一个时间段内的等待,只针对一个element生效。

实例:在20s内直到找到element为止。

from selenium.webdriver.support.ui import WebDriverWaitclass WebDriver:    def __init__(self,driver_path=config_u.get_driver_path):        path = Service(driver_path)        self.driver = webdriver.Firefox(service=path)        self.mouse = ActionChains(self.driver)           	def find_element_xpath(self,xpath_path,key_word):     	self.driver.find_element(By.XPATH,xpath_path).send_keys(key_word)    def element_webdriverwait(self,sec,element):        driver_wait = WebDriverWait(self.driver,sec)        driver_wait.until(lambda x: x.find_element_xpath(By.XPATH,element))

转载地址:https://blog.csdn.net/xiaoqiukuzi/article/details/129164641 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python自动化9 处理常见自动化场景方法(批量处理一组对象、层级定位、网页嵌套定位、弹窗识别(js弹窗))
下一篇:python自动化7 键盘事件

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月25日 17时18分59秒