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")
相关推荐
deephub22 分钟前
机器学习特征工程:缩放、编码、聚合、嵌入与自动化
人工智能·python·机器学习·特征工程
科雷软件测试5 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
派大星~课堂8 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
Thomas.Sir8 小时前
第一章:Agent智能体开发实战之【初步认识 LlamaIndex:从入门到实操】
人工智能·python·ai·检索增强·llama·llamaindex
ZTL-NPU8 小时前
Jetbrains开发ros
ide·python·pycharm·编辑器·ros·clion
环黄金线HHJX.9 小时前
TSE框架配置与部署详解
开发语言·python
前端摸鱼匠9 小时前
YOLOv11与OpenCV 联动实战:读取摄像头实时视频流并用 YOLOv11 进行检测(三)
人工智能·python·opencv·yolo·目标检测·计算机视觉·目标跟踪
Pyeako9 小时前
PyQt5 + PaddleOCR实战:打造桌面级实时文字识别工具
开发语言·人工智能·python·qt·paddleocr·pyqt5
喝凉白开都长肉的大胖子10 小时前
在 Matplotlib 中fontweight一般怎么设置
python·matplotlib
HAPPY酷11 小时前
Python高级架构师之路——从原理到实战
java·python·算法