Selenium时间等待_显示等待

打印 上一主题 下一主题

主题 532|帖子 532|积分 1611

特点:

   

  • 针对具体元素进行时间等待
  • 可以自定义等待时长和隔断时间
  • 按照设定的时间,不断定位元素,定位到了直接执行下一步操作
  • 如在设定时间内没定位到元素,则报错(TimeOutException)
  显示等待概念:

   设置一个等待时间和一个条件,在规定时间内,每隔一段时间检察下条件是否成立,如果成立那么程序就继续执行,否则就提示一个超时异常(TimeoutException)。
  在利用显示等待时,需要联合Selenium的WebDriverWait和expected_conditions模块来实现。


  • WebDriverWait负责等待的设置,
  • expected_conditions模块提供了一系列常用的条件,可以根据具体的需求选择合适的条件
需要导入两个包

  1. # 导入selenium模块中的WebDriverWait类,用于等待特定条件出现后再执行下一步操作
  2. from selenium.webdriver.support.ui import WebDriverWait
  3. # 导入selenium模块中的expected_conditions模块的EC别名,用于定义预期条件
  4. from selenium.webdriver.support import expected_conditions as EC
复制代码
利用步骤:

   1)初始化WebDriverWait对象,指定等待时间和欣赏器驱动。
        eg:wait = WebDriverWait(driver, timeout=3)
  2)调用until方法,传入要等待的条件。
       eg:wait.until(condition)
  3)condition条件通过:expected_conditions as EC 调用指定条件
       eg:wait.until(EC.condition)
  3)在until方法中,会不断地轮询条件是否满足,直到条件满足或超时时间到达。尚有                 until_not()正好与until相反
  4)条件满足后,继续执行后续代码。
  5)如果超过超时时间后仍未满足条件,则抛出TimeoutException异常。
  WebDriverWait参数说明:

   WebDriverWait(driver, timeout=3).until(some_condition)
driver:欣赏器驱动对象
timeout:最长等待时间
  轮询时间:默认是以每500ms轮询一次,也可以指定
.until(some_condition):调用until()方法并传递一个特定的条件some_condition。该方法将等待直到条件满足或超时时间到达
  


这里是一个利用until()方法的例子,它等待页面标题包罗特定文本:
  1. from selenium import webdriver
  2. from selenium.webdriver.support.ui import WebDriverWait
  3. from selenium.webdriver.support import expected_conditions as EC
  4. # 创建WebDriver实例,并指定使用Chrome浏览器驱动
  5. driver = webdriver.Chrome()
  6. # 导航到菜鸟教程网页
  7. driver.get("https://www.runoob.com/")
  8. # 显式等待直到页面标题包含“菜鸟教程”
  9. wait = WebDriverWait(driver, 10)
  10. title_contains_runoob = EC.title_contains("菜鸟教程")
  11. title = wait.until(title_contains_runoob)
  12. # 输出页面标题
  13. print(title)
  14. # 关闭浏览器
  15. driver.quit()
复制代码
这里是一个利用until_not()方法的例子,它等待文本框中的值被扫除:
  1. from selenium import webdriver
  2. from selenium.webdriver.support.ui import WebDriverWait
  3. from selenium.webdriver.support import expected_conditions as EC
  4. # 创建WebDriver实例,并指定使用Chrome浏览器驱动
  5. driver = webdriver.Chrome()
  6. # 导航到百度网页
  7. driver.get("https://www.baidu.com")
  8. # 获取文本框元素并输入文本
  9. input_elem = driver.find_element("css selector", "input[name='wd']")
  10. input_elem.send_keys("python")
  11. # 显式等待直到文本框中的值被清除
  12. wait = WebDriverWait(driver, 10)
  13. value_cleared = EC.text_to_be_present_in_element_value(("css selector", "input[name='wd']"), "")
  14. input_elem.clear()
  15. wait.until_not(value_cleared)
  16. # 关闭浏览器
  17. driver.quit()
复制代码
expected_conditions as EC 条件方法

先导包
  1. # 导入expected_conditions类,并取别名为 EC
  2. from selenium.webdriver.support import expected_conditions as EC
复制代码
条件1:title_is

检查页面标题的期望。title是预期的标题,必须完全匹配如果标题匹配,则返回True,否则返回false。
  1. from selenium.webdriver.support.wait import WebDriverWait
  2. from selenium.webdriver.support import expected_conditions as EC
  3. from selenium import webdriver
  4. # 实例化驱动对象
  5. driver = webdriver.Chrome()
  6. driver.get("http://shop.aircheng.com/simple/login")
  7. # 显示等待 页面标题
  8. # 等待10s
  9. wait = WebDriverWait(driver, 5)
  10. # 获取页面标题
  11. title = driver.title  # 用户登录 - iWebShop商城演示
  12. # title:"预期标题"  message:提示消息
  13. wait.until(EC.title_is(title="用户登录 - iWebShop商城演示3"), message='标题不匹配')
  14. print(title)
复制代码
  1. # 不匹配报错
  2. D:\Scripts\python.exe D:\桌面\Hualenium_demo_6_1\demo9\显示等待2.py
  3. Traceback (most recent call last):
  4.   File "D:\桌面\HuaCe_Python\code_py\selenium_demo_6_1\demo9\显示等待2.py", line 15, in <module>
  5.     wait.until(EC.title_is(title="用户登录 - iWebShop商城演示3"), message='标题不匹配')
  6.   File "D:\桌面\HuaCe_Python\code_py\selenium_demo_6_1\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 105, in until
  7.     raise TimeoutException(message, screen, stacktrace)
  8. selenium.common.exceptions.TimeoutException: Message: 标题不匹配
复制代码
条件2:title_contains

检查标题是否包罗区分大小写的子字符串。title是所需的标题片断当标题匹配时返回True,否则返回False
用法与title_is一样,唯一区别就是:


  • title_is是完全相称,
  • title_contains是包罗
条件3:presence_of_element_located

检查元素是否存在于页面。这并不一定意味着元素是可见的。定位器-用于查找元素找到WebElement后返回该WebElemen
  1. #导包
  2. from selenium.webdriver.support.wait import WebDriverWait
  3. from selenium.webdriver.support import expected_conditions as EC
  4. from selenium.webdriver.common.by import By
  5. from selenium import webdriver
  6. class Brouser:
  7.     fox = webdriver.Firefox()
  8.     wait = WebDriverWait(fox, 5)
  9.     def get_url(self,url):
  10.         self.fox.get(url)
  11.     def presence_located(self,value,*ele):
  12.         el = self.wait.until(EC.presence_of_element_located(ele),message='没有发现期望的元素')
  13.         el.send_keys(value)
  14. if __name__ == '__main__':
  15.     b = Brouser()
  16.     b.get_url('http://shop.aircheng.com/simple/login')
  17.     b.presence_located('qingan',By.NAME,'login_info')
复制代码
条件4:visibility_of_element_located

检查元素是否存在于页面和可见。可见性意味着不仅显示元素但其高度和宽度也大于0。定位器-用于查找元素找到并可见WebElement后返回该WebElement
用法与presence_of_element_located一样,唯一区别就是:


  • visibility_of_element_located:检查元素是否出现,元素为:可见或不可见
  • presence_of_element_located:检查元素是否出现,元素必须为:可见
条件5:url_to_be

检查当前url的期望值。url是预期的url,必须完全匹配。如果url匹配,则返回True,否则返回false
  1. from selenium.webdriver.support.wait import WebDriverWait
  2. from selenium.webdriver.support import expected_conditions as EC
  3. from selenium.webdriver.common.by import By
  4. from selenium import webdriver
  5. class Brouser:
  6.     fox = webdriver.Firefox()
  7.     wait = WebDriverWait(fox, 5)
  8.     def get_url(self,url):
  9.         self.fox.get(url)
  10.     def url_be(self,url):
  11.         self.wait.until(EC.url_to_be(url))
  12. if __name__ == '__main__':
  13.     b = Brouser()
  14.     b.get_url('http://shop.aircheng.com/simple/login')
  15.     b.url_be('http://shop.aircheng.com/simple/login')
复制代码
判断url尚有另外的几种方式,都大同小异
   

  • url_matches: 检查当前url的期望值。pattern是预期的模式,必须是完全匹配的如果url匹配,则返回True,否则返回false。
  • url_contains: 检查当前url是否包罗区分大小写的子字符串。url是所需url的片断,url匹配时返回True,否则返回False
  • url_changes : 检查当前url的期望值。url是预期的url,不能完全匹配如果url不同,则返回True,否则返回false。
  条件6:visibility_of

检查已知存在于页面的DOM是可见的。可见性意味着元素不仅仅是显示,但高度和宽度也大于0。元素是WebElement在WebElement可见时返回(相同的)WebElement
  1. from selenium.webdriver.support.wait import WebDriverWait
  2. from selenium.webdriver.support import expected_conditions as EC
  3. from selenium.webdriver.common.by import By
  4. from selenium import webdriver
  5. class Brouser:
  6.     fox = webdriver.Firefox()
  7.     wait = WebDriverWait(fox, 5)
  8.     def get_url(self,url):
  9.         self.fox.get(url)
  10.     def visibility_(self,*ele):
  11.         el = self.wait.until(EC.visibility_of(self.fox.find_element(*ele)))
  12.         el.click()
  13. if __name__ == '__main__':
  14.     b = Brouser()
  15.     b.get_url('http://shop.aircheng.com/simple/login')
  16.     b.visibility_(By.NAME, 'remember')
复制代码
这里值得留意的是
   visibility_of_element_located跟visibility_of很雷同。与上面的写法不同EC.visibility_of里面写的是定位,而非单纯的元素。这也是一个区别点。在后续的利用中留意一下。
  代码示例1

  1. """需求:等待页面出现标题"""
  2. # 创建WebDriver实例
  3. driver = webdriver.Chrome()
  4. # 导航到网页
  5. driver.get("https://www.csdn.net")
  6. # 等待页面标题包含"CSDN"
  7. wait = WebDriverWait(driver, 5)
  8. title_contains_csdn = EC.title_contains("CSDN")
  9. wait.until(title_contains_csdn)
  10. # 输出页面标题
  11. print(driver.title)
复制代码
代码示例2

  1. # 导包
  2. from selenium.webdriver.support.wait import WebDriverWait
  3. from selenium.webdriver.support import expected_conditions as EC
  4. # 默认是以每500ms轮询一次until中的条件,传入的超时时间是10s
  5. WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID,'kw')))
  6. # 设置每1s轮询一次until中的条件,传入的超时时间是10s
  7. WebDriverWait(driver,10,1).until(EC.presence_of_element_located((By.ID,'kw')))
复制代码
 自定义封装-显示等待

  1. class BackLogin:
  2.     @classmethod
  3.     def wait(cls, driver, func):
  4.         return WebDriverWait(driver, 5).until(func)
  5.     # need_wait:形参代表默认值False不需要触发显示等待
  6.     def find_element(self, by, value, driver, need_wait=False):
  7.         def f(driver):
  8.             # 判断当前元素是否有文本属性
  9.             if driver.find_element(by, value).text:
  10.                 msg = driver.find_element(by, value).text
  11.                 if need_wait:  # 是否触发隐式等待,返回实际提示信息结果
  12.                     return msg
  13.                 else:
  14.                     return True
  15.             else:
  16.                 return True
  17.         # 类中可以通过self对象调用类方法
  18.         self.wait(driver, f)
  19.         return driver.find_element(by, value)
复制代码
调用
  1. # 获取实际结果
  2. msg = BackLogin().find_element(*BackLogin.res_txt, driver,need_wait=True).text
  3. print(msg)
  4. assert msg == "验证码不能为空"
复制代码


参考博客:Selenium 等待方式详解_selenium等待元素可见-CSDN博客
selenium--显示等待(中)--详解篇_presenceofelementlocated-CSDN博客

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

大连全瓷种植牙齿制作中心

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表