Selenium等待事件Waits

一、基础介绍

浏览器载入一个页面时,页面内的元素可能是在不同的时间载入的,这会加大定位元素的困难程度,为了让Selenium可以智能地等待网页加载完成,就需要使用“WebDriverWait”和“EC”

基本格式

WebDriverWait(driver,10).until(EC.presence_of_element_located())

例子

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(r'C:\\tools\\chromedriver.exe')
driver.get("https://exercise.kingname.info/exercise_advanced_ajax.html")
try:
    WebDriverWait(driver,30).until(EC.text_to_be_present_in_element((By.CLASS_NAME,"content"),'通关'))
except Exception as _:
    print('不等了')

element = driver.find_element(By.XPATH,'//div[@class="content"]')
print(f'网站加载的内容是{element.text}')
driver.quit()

EC模块预期条件

  1. 这两个条件类验证title,验证传入的参数title是否等于或包含于driver.title
    title_is
    title_contains
  2. 一个只要一个符合条件的元素加载出来就通过;另一个必须所有符合条件的元素都加载出来才行
    presence_of_element_located
    presence_of_all_elements_located
  3. 这三个条件验证元素是否可见,前两个传入参数是元组类型的locator,第三个传入WebElement,第一个和第三个其实质是一样的
    visibility_of_element_located
    invisibility_of_element_located
    visibility_of
  4. 这两个人条件判断某段文本是否出现在某元素中,一个判断元素的text,一个判断元素的value
    text_to_be_present_in_element
    text_to_be_present_in_element_value
  5. 这个条件判断frame是否可切入,如果可切入就执行切入。可传入locator元组或者直接传入定位方式:id、name、index或WebElement
    frame_to_be_available_and_switch_to_it
  6. 这个条件判断是否有alert出现
    alert_is_present
  7. 这个条件判断元素是否可点击,传入locator
    element_to_be_clickable
  8. 这四个条件判断元素是否被选中,第一个条件传入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
  9. 这个方法用于判断新窗口是否打开,传入打开新窗口之前的window_handles
    new_window_is_opened
  10. 这4 个方法是校验URL的,分别是检查当前url是否包含,pattern是预期的模式,检查当前url的期望,不相等返回true
    url_contains
    url_matches
    url_to_be
    url_changes
posted @ 2024-11-25 21:54  Sonoop  阅读(47)  评论(0)    收藏  举报