Selenium 读 Selenium2Library 的一点疑惑

hxh · 2018年04月03日 · 最后由 恒温 回复于 2018年04月04日 · 1473 次阅读

最近在读 Selenium2Library 的源码,读到一段代码理解不了,求大神指点。

class _ElementKeywords(KeywordGroup):

    def __init__(self):
        self._element_finder = ElementFinder()

    # Public, get element(s)

    def _element_find(self, locator, first_only, required, tag=None):
        browser = self._current_browser()
        if isstr(locator):
            elements = self._element_finder.find(browser, locator, tag)
            if required and len(elements) == 0:
                raise ValueError("Element locator '" + locator + "' did not match any elements.")
            if first_only:
                if len(elements) == 0: return None
                return elements[0]
        elif isinstance(locator, WebElement):
            elements = locator
        # do some other stuff here like deal with list of webelements
        # ... or raise locator/element specific error if required
        return elements

_element_find是 Selenium2Library 定义的查找 web element 的方法,第一句是获取当前的 webdriver。但是_current_browser() 不是_ElementKeywords这个类定义的,而是在_BrowserManagementKeywords这个类定义的。那么为什么在_ElementKeywords里面可以用self._current_browser()调用_BrowserManagementKeywords定义的方法?

class _BrowserManagementKeywords(KeywordGroup):

    def __init__(self):
        self._cache = BrowserCache()
        self._window_manager = WindowManager()
        self._speed_in_secs = float(0)
        self._timeout_in_secs = float(5)
        self._implicit_wait_in_secs = float(0)

    # Public, open and close

    def _current_browser(self):
        if not self._cache.current:
            raise RuntimeError('No browser is open')
        return self._cache.current

_ElementKeywords_BrowserManagementKeywords有共同的父类KeywordGroup。是否是因为它们的父类是由KeywordGroupMetaClass这个元类定义的?

class KeywordGroupMetaClass(type):
    def __new__(cls, clsname, bases, dict):
        if decorator:
            for name, method in dict.items():
                if not name.startswith('_') and inspect.isroutine(method):
                    dict[name] = decorator(_run_on_failure_decorator, method)
        return type.__new__(cls, clsname, bases, dict)

class KeywordGroup(object):
    __metaclass__ = KeywordGroupMetaClass

以上,求大神指点

共收到 5 条回复 时间 点赞

你说的很对

hxh #2 · 2018年04月03日 Author
恒温 回复

能具体解释一下吗?不是很理解,上述也只是我的猜测。😅

hxh 回复

我也是猜测的啊。。。

@hxhapppppy 看这个项目的 init.py 文件 你就知道为啥了。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册