简体   繁体   中英

Selenium WebElement extension method in Python

Wanted to ask if there is a chance to create so called extension method for WebElement class within Selenium/Appium framework. I realize that Python does not have extension methods, but some things can be achieved with monkey patching, however I've been strugling to do so.

Let me show it on example

In my framework I have function for looking for elements:

    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

Now as I already have found the element which is object of WebElement class I would like to execute the same function as above on this element, to find another element(child, descendant) inside.

Is it possible to achive such a thing in Python? I did this in C# but in this case I'm helpless.

That would make it easier for me to write tests for my apps

You could do the following which I think is a clean and proper oop way to handle it:

Make a custom WebElement class which ofcourse inherits from WebElement:

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

Make a custom WebDriver class which ofcourse inherits from WebDriver

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

Explanation: The class stored in _web_element_cls is being returned everytime your search for elements. If we dive deeper into the code of selenium we see that WebDriver calls find_element(s) method as a "base" function for searching elements, which eventually calls create_web_element method and in this method a WebElement is created with the class stored in _web_element_cls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM