Python中的Selenium WebElement扩展方法

时间:2018-03-09 16:23:07

标签: python selenium selenium-webdriver appium monkeypatching

想知道是否有机会在Selenium / Appium框架内为WebElement类创建所谓的扩展方法。 我意识到Python没有扩展方法,但有些东西可以通过猴子修补来实现,但是我一直在努力这样做。

让我在示例中显示它

在我的框架中,我有查找元素的功能:

    def find_element_with_wait(self, findby_and_locator, time_to_wait=5, dynamicaly_created=False):
    """Finds element on the screen with 5 seconds timeout as default. Timeout can be specified in function parameters as integer. Returns WebElement if element exists and None whene there is no such element"""
    find_by, selector = None, None

    if isinstance(findby_and_locator, dict):
        if DeviceData()._platformName == 'iOS':
            find_by, selector = findby_and_locator.get('iOS')
        else:
            find_by, selector = findby_and_locator.get('Android')

    elif isinstance(findby_and_locator, tuple):
        find_by, selector = findby_and_locator

    self._wait_for_DOM_presence(find_by, selector, time_to_wait)

    try:
        element = self.driver.find_element(find_by, selector)
    except NoSuchElementException:
        print(' Seeked element was not found. Return element = None')
        element = None

现在我已经找到了元素这是WebElement类的对象,我想在这个元素上执行与上面相同的功能,以找到里面的另一个元素(子,后代)。 / p>

是否可以在Python中实现这样的功能?我是用C#做的,但在这种情况下我很无奈。

这样我就可以更轻松地为我的应用编写测试

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作,我认为这是处理此问题的一种干净而正确的方法:

制作一个自定义WebElement类,该类当然是从WebElement继承的:

class CustomElement(WebElement):
    ...your custom functions here

制作一个自定义WebDriver类,该类当然是从WebDriver继承的

class CustomWebDriver(WebDriver):
    _web_element_cls = CustomElement
    ...your custom functions here

说明: 每次搜索元素时,都会返回存储在_web_element_cls中的类。 如果深入研究Selenium代码,我们会发现WebDriver调用find_element(s)方法作为搜索元素的“基础”函数,最终会调用create_web_element方法,并在此方法中使用存储在_web_element_cls中的类创建WebElement。 / p>