• Selenium(Python)等待元素出现


    1、显式等待

    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.Firefox()
    driver.get("http://somedomain/url_that_delays_loading")
    try:
    element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
    finally:
    driver.quit()

    除非在10秒内发现元素返回,
    否则在抛出TimeoutException之前等待10秒,
    WebDriverWait默认每500毫秒调用一次ExpectedCondition,
    直到它成功返回,
    ExpectedCondition的成功返回类型是布尔值,
    对于所有其他ExpectedCondition类型,
    返回true或非null返回值。

    预期条件,
    自动化网页浏览器时经常使用一些常见条件:

    from selenium.webdriver.support import expected_conditions as EC

    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))


    下面列出每个的名称:

    title_is
    title_contains
    presence_of_element_located
    visibility_of_element_located
    visibility_of
    presence_of_all_elements_located
    text_to_be_present_in_element
    text_to_be_present_in_element_value
    frame_to_be_available_and_switch_to_it
    invisibility_of_element_located
    element_to_be_clickable
    staleness_of
    element_to_be_selected
    element_located_to_be_selected
    element_selection_state_to_be
    element_located_selection_state_to_be
    alert_is_present

    自定义等待条件:

    如果以上的便利方法都不符合你的要求,
    您还可以创建自定义等待条件,
    可以使用具有__call__方法的类创建自定义等待条件,
    该条件在条件不匹配时返回False。

    class element_has_css_class(object):
    """期望检查某个元素是否具有特定CSS类
    locator-用于查找元素

    返回WebElement一旦它具有特定的CSS类
    """
    def __init__(self, locator, css_class):
    self.locator = locator
    self.css_class = css_class

    def __call__(self, driver):
    element = driver.find_element(*self.locator)
    # 查找引用的元素
    if self.css_class in element.get_attribute("class"):
    return element
    else:
    return False

    wait = WebDriverWait(driver, 10)
    element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass"))
    # 等到ID = "myNewInput"元素有类"myCSSClass"


    2、隐式等待

    from selenium import webdriver

    driver = webdriver.Firefox()
    driver.implicitly_wait(10)
    driver.get("http://somedomain/url_that_delays_loading")
    myDynamicElement = driver.find_element_by_id("myDynamicElement")

  • 相关阅读:
    经济危机下,自主创业已成为一种时代潮流?
    曾靖雯(帮别人名字作诗)
    四大内伤造就80后创业高失败率
    如何让创业的路不再崎岖
    叶莉(帮别人名字作诗)
    谁能够在萧条中生存?历史总是惊人相似的(转)
    哪种书最适合创业者阅读
    中西部崛起 关键是要激发普遍的创业热情
    每日英语:Dating in China Is a Largely Commercial Transaction
    每日英语:Poor Chinese Schools Tell Students: Bring Your Own Desks
  • 原文地址:https://www.cnblogs.com/yjlch1016/p/8570459.html
Copyright © 2020-2023  润新知