Skip to main content
 首页 » 编程设计

python之如何在新的 python 关键字文件中共享当前浏览器(webdriver)对象

2024年08月14日45luoye11

我使用下面的代码但它返回:RuntimeError('No browser is open')

class UtilityFunction(ExtendedSelenium2Library): 
    ROBOT_LIBRARY_SCOPE = 'GLOBAL' 
 
    def __init__(self): 
        # super.__init__() 
        self.lib = BuiltIn().get_library_instance('ExtendedSelenium2Library') 
        self.driver=self.lib._current_browser() 

请您参考如下方法:

__init__() 中的代码在对象初始化时运行 - 在 Robot Framework 中,当库被导入时(在文件的开头)。那时,没有打开的浏览器——您还没有运行套件设置,关键字 Open Browser 还没有运行;因此异常(exception)。

“修复”是不在构造函数中获取 webdriver 的实例:

def __init__(self): 
    # super.__init__() 
    self.lib = BuiltIn().get_library_instance('ExtendedSelenium2Library') 
    self._driver = None  # internal attribute, don't use it in the methods, but "self.driver" 
 
@property 
def driver(self): 
    if self._driver is None: 
        self._driver=self.lib._current_browser() 
    return self._driver 
 
@driver.setter 
def driver(self, custom): 
    self._driver=custom 

此方法使用 class properties - 自动 getter 和 setter ;当你的代码使用self.driver时,如果它的值没有定义(还是None),它会自动赋值给self.lib._current_browser的返回值()。