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")
相关推荐
树獭非懒10 小时前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习13 小时前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽15 小时前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama
Flittly15 小时前
【从零手写 AI Agent:learn-claude-code 项目实战笔记】(1)The Agent Loop (智能体循环)
python·agent
vivo互联网技术17 小时前
ICLR2026 | 视频虚化新突破!Any-to-Bokeh 一键生成电影感连贯效果
人工智能·python·深度学习
敏编程18 小时前
一天一个Python库:virtualenv - 隔离你的Python环境,保持项目整洁
python
喝茶与编码20 小时前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
zone773920 小时前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
用户83562907805121 小时前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python