Selenium-等待元素可见

# coding=utf-8

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


def element_path_visible(driver, element_path, timeout=10):
    """
    等待某元素可见,默认超时10秒
    :param driver:
    :param element_path:元素路径
    :param timeout: 超时时间
    :return: 等待结果
    """
    try:
        ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.XPATH, element_path)))
        return True
    except TimeoutException:
        return False


def element_class_visible(driver, element_class, timeout=10):
    """
    等待某元素可见,默认超时10秒
    :param driver:
    :param element_class:元素路径
    :param timeout: 超时时间
    :return: 等待结果
    """
    try:
        ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CLASS_NAME, element_class)))
        return True
    except TimeoutException:
        return False


def element_css_selector_visible(driver, element_selector, timeout=20):
    """
    等待某元素可见,默认超时10秒
    :param driver:
    :param element_selector:元素路径
    :param timeout: 超时时间
    :return: 等待结果
    """
    try:
        ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CSS_SELECTOR, element_selector)))
        return True
    except TimeoutException:
        return False


def element_path_not_visible(driver, element_path, timeout=20):
    """
    等待某个元素消失,默认超时10秒
    :param driver:
    :param element_path: 元素路径
    :param timeout: 超时时间
    :return:
    """
    try:
        ui.WebDriverWait(driver, timeout).until_not(EC.visibility_of_element_located((By.XPATH, element_path)))
        return True
    except TimeoutException:
        return False


def get_element(driver, element, element_type="class_name"):
    """
    根据元素xpath,class_name,css_selector等获取元素
    :param driver:
    :param element:
    :param element_type:元素路径类型
    :return:
    """
    if element_type == "xpath":
        element_path_visible(driver, element)
        return driver.find_element_by_xpath(element)
    elif element_type == "class_name":
        element_class_visible(driver, element)
        return driver.find_elements_by_class_name(element)
    elif element_type == "css_selector":
        css_selector = "[class='{}']".format(element)
        element_css_selector_visible(driver, css_selector)
        return driver.find_elements_by_css_selector(css_selector)
    else:
        pass

你可能感兴趣的:(Selenium-等待元素可见)