相信看了工厂模式的简介,一定能懂这样的设计思路了吧
我把这段代码比作什么工厂好呢,就叫它: Driver工厂
已配置环境的driver、没有配置的(准备用 .exe)、使用selenium gird的工厂
当然使用gird的driver工厂,你需要传入的是master-node-url
import abc
from abc import ABC
from selenium import webdriver
from conf.ErrorConfig import GETDRIVERERROR, BROWEREXPECTION
from selenium.webdriver.chrome.webdriver import WebDriver
from conf.PathConfig import DRIVER_DIR
class Driver(ABC):
driver = None
@abc.abstractmethod
def product_driver(self, *args, **kwargs):
pass
@classmethod
def get_driver(cls, *args, **kwargs) -> WebDriver:
if cls.driver is None:
try:
cls.driver: WebDriver = cls().product_driver(*args, **kwargs)
cls.driver.maximize_window()
except:
raise GETDRIVERERROR
return cls.driver
else:
return cls.driver
class Local(Driver):
"""
访问本地环境变量
"""
def product_driver(self, browertype='chrome', debug=False):
if debug:
options = webdriver.ChromeOptions()
options.debugger_address = "127.0.0.1:9222"
driver = webdriver.Chrome(options=options)
else:
if browertype == 'firefox':
driver = webdriver.Firefox()
elif browertype == 'chrome':
driver = webdriver.Chrome()
else:
raise BROWEREXPECTION
return driver
class test(Driver):
"""
未配置chromedriver环境变量
"""
def product_driver(self, *args, **kwargs):
driver = webdriver.Chrome(executable_path=DRIVER_DIR + 'chromedriver.exe')
return driver
class Grid(Driver):
def product_driver(self, selenium_grid_url, brower='chrome'):
"""
selenium gird
:param selenium_grid_url: 访问gird server-node地址
:param brower:
:return:
"""
des = webdriver.DesiredCapabilities
if brower == 'firefox':
capablities = des.FIREFOX.copy()
elif brower == 'chrome':
capablities = des.CHROME.copy()
else:
raise
driver = webdriver.Remote(command_executor=selenium_grid_url,
desired_capabilities=capablities)
return driver
class DriverFactory:
"""
DriverFacory FOR chrome Firefox..
"""
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(DriverFactory, "_instance"):
DriverFactory._instance = object.__new__(cls)
return DriverFactory._instance
@staticmethod
def chooseBrower(env: str = 'test'):
"""
choose env to product driver
:param env:
:param
:return:
"""
map_ = {"local": Local,
'test': test,
"grid": Grid}
if map_.get(env, None) is None:
raise BROWEREXPECTION(env)
return map_[env.lower()]
if __name__ == "__main__":
dri = DriverFactory().chooseBrower("test").get_driver()
dri.get('https://www.baidu.com')
看到结束
白嫖不能忍,请发一次文