我为selenium webdriver创建了一个单独的包装器。
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Driver(metaclass=Singleton):
"""Ensures theres only 1 Driver open at any time.
If the driver is closed, tries to quit the previous
instance, and recreates a new one"""
def __init__(self):
self._driver = self.load_selenium_driver()
@staticmethod
def load_selenium_driver():
_chrome_driver_locn = CHROME_DRIVER_LOCATION
_driver = webdriver.Chrome(_chrome_driver_locn)
return _driver
@property
def driver(self):
"""Creates a new driver if the previous one is closed,
and quits the instance of the chrome driver."""
if self._web_browser_is_open():
return self._driver
else:
try:
self._driver.quit()
finally:
self._driver = self.load_selenium_driver()
return self._driver
def _web_browser_is_open(self):
try:
self._driver.title
return True
except WebDriverException:
return False
正在运行a = Driver()
我想访问Driver.driver
中的a
方法,这样我就不需要a.driver.get('google.com')
,而是a.get('google.com')
。
问题:
如何创建Driver实例,返回driver
对象(在属性Driver.driver
中找到),而不是Driver
的实例?
答案 0 :(得分:0)
从评论中的讨论来看,我所要求的是不可能的。