Python selenium封装元素定位FindElement工具类

复制代码
# coding=utf-8
from config.setting_base import SettingBase
from util.read_ini import ReadIni
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ES
from contextlib import contextmanager


class FindElement(object):
    def __init__(self, driver, file_name=None, node=None):
        self.driver = driver
        self.read_ini = ReadIni(file_name=file_name, node=node)
        self.locator = ()# 配置文件中定位元素的方式,如:id,name,xpath
    def get_by_key(self, key):
        data = self.read_ini.get_value(key)
        by_key = data.split('>')[0].strip()
        return by_key

    # 配置文件的value
    def get_value(self, key):
        data = self.read_ini.get_value(key)
        value = data.split('>')[1].strip()
        return valuedef selector_to_locator(self, key):
        selector_by = self.get_by_key(key)
        selector_value = self.get_value(key)
        if selector_by == 'id':
            locator = (By.ID, selector_value)
        elif selector_by == 'name':
            locator = (By.NAME, selector_value)
        elif selector_by == 'class_name':
            locator = (By.CLASS_NAME, selector_value)
        elif selector_by == 'link_text':
            locator = (By.PARTIAL_LINK_TEXT, selector_value)
        elif selector_by == 'tag_name':
            locator = (By.TAG_NAME, selector_value)
        elif selector_by == 'xpath':
            locator = (By.XPATH, selector_value)
        elif selector_by == 'css_selector':
            locator = (By.CSS_SELECTOR, selector_value)
        else:
            raise NameError("Please enter a valid selector of targeting elements.")
        return locator

    @contextmanager
    def find_base(self, key):
        if not isinstance(key, tuple):
            self.locator = self.selector_to_locator(key)
        else:
            self.locator = key
        if isinstance(self.locator, tuple):
            try:
                yield
            except:
                print(f"定位失败:定位方式->{self.locator[0]}, value值->{self.locator[1]}")
                return False

    def find(self, key, timeout=None, value=None):
        """
        页面查找单个元素
        :param key: 元素的元组(By, value)
        :param timeout: 超时时间
        :param value: 需要查找的值
        """
        with self.find_base(key):
            if timeout is None:
                timeout = SettingBase.UI_WAIT_TIME
            ele = self.__find_value(self.locator, timeout, value)
            return ele

    def not_find(self, key, timeout=None, value=None):
        """
        页面查找没有此元素
        :param key: 元素的元组(By, value)
        :param timeout: 超时时间
        :param value:需要查找的值
        """
        with self.find_base(key):
            if timeout is None:
                timeout = SettingBase.UI_WAIT_TIME
            self.__not_find_value(self.locator, timeout, value)

    def __find_value(self, locator, timeout, value):
        if value is None:
            # presence_of_element_located 不关心元素是否可见,只要元素存在在页面中即可
            ele = WebDriverWait(self.driver, timeout, SettingBase.POLL_FREQUENCY).until(
                 ES.presence_of_element_located(locator))
        else:
            # 判断元素中是否存在指定的文本,返回布尔值
            ele = WebDriverWait(self.driver, timeout, SettingBase.POLL_FREQUENCY).until(
                ES.text_to_be_present_in_element(locator, value))
        return ele

    def __not_find_value(self, locator, timeout, value):
        if value is None:
            # presence_of_element_located 不关心元素是否可见,只要元素存在在页面中即可
            bools = WebDriverWait(self.driver, timeout, SettingBase.POLL_FREQUENCY).until_not(
                ES.presence_of_element_located(locator))
        else:
            # 判断元素中是否存在指定的文本,返回布尔值
            bools = WebDriverWait(self.driver, timeout, SettingBase.POLL_FREQUENCY).until_not(
                ES.text_to_be_present_in_element(locator, value))
        return bools

    def finds(self, key, timeout=None):
        """
        页面查找多个元素
        :param key: 元素的元组(By, value)
        :param timeout: 超时时间
        :return: list or False
        """
        with self.find_base(key):
            if timeout is None:
                timeout = SettingBase.UI_WAIT_TIME
            # presence_of_all_elements_located 等待所有locator元素都加载出来,返回list
            eles = WebDriverWait(self.driver, timeout, SettingBase.POLL_FREQUENCY).until(
                ES.presence_of_all_elements_located(self.locator))
            return eles

    def find_title(self, key, timeout=None):
        """
        title中包含元素
        :param key: 元素的元组(By, value)
        :param timeout: 超时时间
        :return: True when the title matches, False otherwise
        """
        with self.find_base(key):
            if timeout is None:
                timeout = SettingBase.UI_WAIT_TIME
            # 判断元素中是否存在包含title,返回布尔值
            ele = WebDriverWait(self.driver, timeout, SettingBase.POLL_FREQUENCY).until(
                ES.title_contains(self.locator))
            return ele
复制代码

 

posted @   莫离m  阅读(596)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示