selenium4.x 之POM概况

Page Object Mpde

一、基类

basePage

复制代码
import logging
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
logger = logging.getLogger("PO")


class BasePage:
    """poge的基类"""

    def __init__(self, driver: webdriver.Chrome):
        self._driver = driver
        self._wait = WebDriverWait(driver, 10)   # 自动等待
        logger.info("PO实例化成功")

    def __getattr__(self, item):
        key = f"_loc_{item}"
        if hasattr(self, key):
            xpath = getattr(self, key)
            return self.get_element(xpath)
        raise AttributeError(f'元素不存在:{item}')

    def get_element(self, xpath):
        logger.info("正在进行元素定位")
        el = self._wait.until(lambda x: self._driver.find_element(By.XPATH, xpath))
        logger.info("元素定位成功")
        return el

    # alert弹窗
    def alert(self):
        time.sleep()

        # alert = driver.switch_to.alert
        def _a():
            return self._driver.switch_to.alert  # 可能会失败,可能会成功

        alert = self._wait.until(_a)
        alert.accept()
    
    # 系统信息
    def get_msg(self):
        time.sleep(0.5)  # 等待-0.5秒
        el = self._driver.find_element(By.XPATH, "//p[@class='prompt-msg']")
        return el.text

Python--getattr反射+selenium详解篇_selenium kwargs.get-CSDN博客

二、页面

page:可以讲属性和方法分开

属性(元素)和方法(元素的操作)

复制代码
class LoginPage(BasePage):
    _loc_code = ('//div/ul/li[@class="account-tab-account"]')
    _loc_username = ('//input[@id="username"]')
    _loc_password = ('//input[@id="password"]')

    def login(self, username, password):
        self.code.click()
        self.username.send_keys(username)
        self.password.send_keys(password)

元素可单独封装

三、测试用例

复制代码
def test_00():
    driver = get_webdriver()
    driver.get("https://accounts.douban.com/passport/login")
    page = LoginPage(driver)
    page.login("12255", "123456")
相关推荐
钱栈up29 分钟前
GitHub热榜实测|Sherlock:一个用户名搜遍全网
python·开源·github
geovindu32 分钟前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
Agent世界1 小时前
发布台账字段漂移:1265 条记录里 190 条没有标题
python·自动化运维
用户298698530143 小时前
Python 自动化处理 Word:按规则查找并高亮关键文本
python·api·编程语言
人工智能技术咨询.4 小时前
什么才算高质量数据集
python
DanCheng-studio4 小时前
毕业设计项目 机器视觉指纹识别特征对比算法(源码+论文)
python·毕业设计·毕设
梅雅达编程笔记4 小时前
一份 PDF 到底该拆成什么存进去:RAG 智能问答毕设数据库设计完整教程
python·flask·智能问答·毕设·向量数据库·rag·数据库设计
AI创界者4 小时前
Python 进阶实战(第八十三章):基于 Redis Lua 脚本的分布式令牌桶限流、异步熔断器状态机与信号优雅关机实战
人工智能·python·aigc
Thanks_ks15 小时前
提示词工程实战:用结构化提示词让大模型输出稳定可控
python·大模型·json·openai·提示词工程·deepseek·系统提示词
BK贝壳17 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy