python工具类-selenium 浏览器封装

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021-12-08 8:52
# @Author  : herry
# @File    : BrowserUtil.py
# @software: PyCharm
# @describe: BrowserUtil
"""
   说明:调用浏览器是需要下载相应的驱动,并放到python 目录下
   chrome:chromeDriver.exe
   FireFox:geckodriver.exe


"""


from selenium import webdriver


from src.util.Logger import Log


log = Log().getlog()
browser = None




def Singleton(cls):
    _instance = {}


    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]


    return _singleton




@Singleton
class Browser:
    """
    单实例对象
    """
    browser = None


    def __init__(self, browser_type="chrome", isHeadLess=False, isMax=True):
        log.info("初始化浏览器")
        if self.browser == None:
            self.browser = initBrowser(browser_type=browser_type, isHeadLess=isHeadLess, isMax=isMax)


    def getBrowser(self):
        return self.browser


    def __del__(self):
        try:
            print("!!!!!")
            self.browser.close()
            print("!2222")
            print("浏览器正常退出")
        except Exception as e:
            print("浏览器退出异常--》%s", e)
            pass




class MBrowser:
    """
    普通多实例对象
    """
    browser = None


    def __init__(self, browser_type="chrome", isHeadLess=False, isMax=True):
        log.info("初始化浏览器")
        if self.browser is None:
            self.browser = initBrowser(browser_type=browser_type, isHeadLess=isHeadLess, isMax=isMax)


    def getBrowser(self):
        return self.browser


    def __del__(self):
        try:
            print("!!!!!")
            self.browser.close()
            print("!2222")
            print("浏览器正常退出")
        except Exception as e:
            print("浏览器退出异常--》%s", e)
            pass




def chromeOption(isHeadLess=False):
    options = webdriver.ChromeOptions()
    if isHeadLess:
        options.add_argument("--headless")


    return options




def firefoxOptions(isHeadLess=False):
    options = webdriver.FirefoxOptions()
    if isHeadLess:
        options.add_argument("--headless")
    return options




def initBrowser(browser_type="chrome", isHeadLess=False, isMax=True):
    try:
        if browser_type == "chrome":
            options = chromeOption(isHeadLess)
            browser = webdriver.Chrome(options=options)
        elif browser_type == "FireFox":
            options = firefoxOptions(isHeadLess)
            browser = webdriver.Firefox(options=options)


        else:
            return "浏览器类型错误,请选择chrome或FireFox"
        if isMax:
            browser.maximize_window()
    except Exception as e:
        log.error("浏览器获取失败-->%s", e)


    return browser

-------------------------------------最后---------------------------------

 更多软件测试相关内容请关注“软件测试道与术”公众号或扫描下方二维码

python工具类-selenium 浏览器封装_第1张图片

你可能感兴趣的:(python,selenium,chrome,java,ajax)