Best Python code snippet using robotframework-pageobjects_python
_element.py
Source:_element.py  
...28        Key attributes for arbitrary elements are `index` and `name`. See29        `introduction` for details about locating elements.30        """31        self._info("Clicking element '%s'." % locator)32        self._element_find(locator, True, True).click()33    def click_button(self, index_or_name):34        """ Click button """35        _platform_class_dict = {'ios': 'UIAButton',36                                'android': 'android.widget.Button'}37        if self._is_support_platform(_platform_class_dict):38            class_name = self._get_class(_platform_class_dict)39            self._click_element_by_class_name(class_name, index_or_name)40    def click_text(self, text, exact_match=False):41        """Click text identified by ``text``.42        By default tries to click first text involves given ``text``, if you would43        like to click exactly matching text, then set ``exact_match`` to `True`.44        If there are multiple use  of ``text`` and you do not want first one,45        use `locator` with `Get Web Elements` instead.46        New in AppiumLibrary 1.4.47        """48        if self._get_platform() == 'ios':49            element = self._element_find(text, True, False)50            if element:51                element.click()52            else:53                if exact_match:54                    _xpath = u'//*[@value="{}" or @label="{}"]'.format(text, text)55                else:56                    _xpath = u'//*[contains(@label,"{}") or contains(@value, "{}")]'.format(text, text)57                self._element_find(_xpath, True, True).click()58        elif self._get_platform() == 'android':59            if exact_match:60                _xpath = u'//*[@{}="{}"]'.format('text', text)61            else:62                _xpath = u'//*[contains(@{},"{}")]'.format('text', text)63            self._element_find(_xpath, True, True).click()64    def input_text(self, locator, text):65        """Types the given `text` into text field identified by `locator`.66        See `introduction` for details about locating elements.67        """68        self._info("Typing text '%s' into text field '%s'" % (text, locator))69        self._element_input_text_by_locator(locator, text)70    def input_password(self, locator, text):71        """Types the given password into text field identified by `locator`.72        Difference between this keyword and `Input Text` is that this keyword73        does not log the given password. See `introduction` for details about74        locating elements.75        """76        self._info("Typing password into text field '%s'" % locator)77        self._element_input_text_by_locator(locator, text)78    def input_value(self, locator, text):79        """Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value80        See `introduction` for details about locating elements.81        """82        self._info("Setting text '%s' into text field '%s'" % (text, locator))83        self._element_input_value_by_locator(locator, text)84    def hide_keyboard(self, key_name=None):85        """Hides the software keyboard on the device. (optional) In iOS, use `key_name` to press86        a particular key, ex. `Done`. In Android, no parameters are used.87        """88        driver = self._current_application()89        driver.hide_keyboard(key_name)90    def page_should_contain_text(self, text, loglevel='INFO'):91        """Verifies that current page contains `text`.92        If this keyword fails, it automatically logs the page source93        using the log level specified with the optional `loglevel` argument.94        Giving `NONE` as level disables logging.95        """96        if not self._is_text_present(text):97            self.log_source(loglevel)98            raise AssertionError("Page should have contained text '%s' "99                                 "but did not" % text)100        self._info("Current page contains text '%s'." % text)101    def page_should_not_contain_text(self, text, loglevel='INFO'):102        """Verifies that current page not contains `text`.103        If this keyword fails, it automatically logs the page source104        using the log level specified with the optional `loglevel` argument.105        Giving `NONE` as level disables logging.106        """107        if self._is_text_present(text):108            self.log_source(loglevel)109            raise AssertionError("Page should not have contained text '%s'" % text)110        self._info("Current page does not contains text '%s'." % text)111    def page_should_contain_element(self, locator, loglevel='INFO'):112        """Verifies that current page contains `locator` element.113        If this keyword fails, it automatically logs the page source114        using the log level specified with the optional `loglevel` argument.115        Giving `NONE` as level disables logging.116        """117        if not self._is_element_present(locator):118            self.log_source(loglevel)119            raise AssertionError("Page should have contained element '%s' "120                                 "but did not" % locator)121        self._info("Current page contains element '%s'." % locator)122    def page_should_not_contain_element(self, locator, loglevel='INFO'):123        """Verifies that current page not contains `locator` element.124        If this keyword fails, it automatically logs the page source125        using the log level specified with the optional `loglevel` argument.126        Giving `NONE` as level disables logging.127        """128        if self._is_element_present(locator):129            self.log_source(loglevel)130            raise AssertionError("Page should not have contained element '%s'" % locator)131        self._info("Current page not contains element '%s'." % locator)132    def element_should_be_disabled(self, locator, loglevel='INFO'):133        """Verifies that element identified with locator is disabled.134        Key attributes for arbitrary elements are `id` and `name`. See135        `introduction` for details about locating elements.136        """137        if self._element_find(locator, True, True).is_enabled():138            self.log_source(loglevel)139            raise AssertionError("Element '%s' should be disabled "140                                 "but did not" % locator)141        self._info("Element '%s' is disabled ." % locator)142    def element_should_be_enabled(self, locator, loglevel='INFO'):143        """Verifies that element identified with locator is enabled.144        Key attributes for arbitrary elements are `id` and `name`. See145        `introduction` for details about locating elements.146        """147        if not self._element_find(locator, True, True).is_enabled():148            self.log_source(loglevel)149            raise AssertionError("Element '%s' should be enabled "150                                 "but did not" % locator)151        self._info("Element '%s' is enabled ." % locator)152    def element_name_should_be(self, locator, expected):153        element = self._element_find(locator, True, True)154        if str(expected) != str(element.get_attribute('name')):155            raise AssertionError("Element '%s' name should be '%s' "156                                 "but it is '%s'." % (locator, expected, element.get_attribute('name')))157        self._info("Element '%s' name is '%s' " % (locator, expected))158    def element_value_should_be(self, locator, expected):159        element = self._element_find(locator, True, True)160        if str(expected) != str(element.get_attribute('value')):161            raise AssertionError("Element '%s' value should be '%s' "162                                 "but it is '%s'." % (locator, expected, element.get_attribute('value')))163        self._info("Element '%s' value is '%s' " % (locator, expected))164    def element_attribute_should_match(self, locator, attr_name, match_pattern, regexp=False):165        """Verify that an attribute of an element matches the expected criteria.166        The element is identified by _locator_. See `introduction` for details167        about locating elements. If more than one element matches, the first element is selected.168        The _attr_name_ is the name of the attribute within the selected element.169        The _match_pattern_ is used for the matching, if the match_pattern is170        - boolean or 'True'/'true'/'False'/'false' String then a boolean match is applied171        - any other string is cause a string match172        The _regexp_ defines whether the string match is done using regular expressions (i.e. BuiltIn Library's173        [http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Should%20Match%20Regexp|Should174        Match Regexp] or string pattern match (i.e. BuiltIn Library's175        [http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Should%20Match|Should176        Match])177        Examples:178        | Element Attribute Should Match | xpath = //*[contains(@text,'foo')] | text | *foobar |179        | Element Attribute Should Match | xpath = //*[contains(@text,'foo')] | text | f.*ar | regexp = True |180        | Element Attribute Should Match | xpath = //*[contains(@text,'foo')] | enabled | True |181        | 1. is a string pattern match i.e. the 'text' attribute should end with the string 'foobar'182        | 2. is a regular expression match i.e. the regexp 'f.*ar' should be within the 'text' attribute183        | 3. is a boolead match i.e. the 'enabled' attribute should be True184        _*NOTE: *_185        On Android the supported attribute names are hard-coded in the186        [https://github.com/appium/appium/blob/master/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/AndroidElement.java|AndroidElement]187        Class's getBoolAttribute() and getStringAttribute() methods.188        Currently supported (appium v1.4.11):189        _contentDescription, text, className, resourceId, enabled, checkable, checked, clickable, focusable, focused, longClickable, scrollable, selected, displayed_190        _*NOTE: *_191        Some attributes can be evaluated in two different ways e.g. these evaluate the same thing:192        | Element Attribute Should Match | xpath = //*[contains(@text,'example text')] | name | txt_field_name |193        | Element Name Should Be         | xpath = //*[contains(@text,'example text')] | txt_field_name |      |194        """195        elements = self._element_find(locator, False, True)196        if len(elements) > 1:197            self._info("CAUTION: '%s' matched %s elements - using the first element only" % (locator, len(elements)))198        attr_value = elements[0].get_attribute(attr_name)199        # ignore regexp argument if matching boolean200        if isinstance(match_pattern, bool) or match_pattern.lower() == 'true' or match_pattern.lower() == 'false':201            if isinstance(match_pattern, bool):202                match_b = match_pattern203            else:204                match_b = ast.literal_eval(match_pattern.title())205            if isinstance(attr_value, bool):206                attr_b = attr_value207            else:208                attr_b = ast.literal_eval(attr_value.title())209            self._bi.should_be_equal(match_b, attr_b)210        elif regexp:211            self._bi.should_match_regexp(attr_value, match_pattern,212                                         msg="Element '%s' attribute '%s' should have been '%s' "213                                             "but it was '%s'." % (locator, attr_name, match_pattern, attr_value),214                                         values=False)215        else:216            self._bi.should_match(attr_value, match_pattern,217                                  msg="Element '%s' attribute '%s' should have been '%s' "218                                      "but it was '%s'." % (locator, attr_name, match_pattern, attr_value),219                                  values=False)220        # if expected != elements[0].get_attribute(attr_name):221        #    raise AssertionError("Element '%s' attribute '%s' should have been '%s' "222        #                         "but it was '%s'." % (locator, attr_name, expected, element.get_attribute(attr_name)))223        self._info("Element '%s' attribute '%s' is '%s' " % (locator, attr_name, match_pattern))224    def element_should_contain_text(self, locator, expected, message=''):225        """Verifies element identified by ``locator`` contains text ``expected``.226        If you wish to assert an exact (not a substring) match on the text227        of the element, use `Element Text Should Be`.228        Key attributes for arbitrary elements are ``id`` and ``xpath``. ``message`` can be used to override the default error message.229        New in AppiumLibrary 1.4.230        """231        self._info("Verifying element '%s' contains text '%s'."232                    % (locator, expected))233        actual = self._get_text(locator)234        if not expected in actual:235            if not message:236                message = "Element '%s' should have contained text '%s' but "\237                          "its text was '%s'." % (locator, expected, actual)238            raise AssertionError(message)239    def element_should_not_contain_text(self, locator, expected, message=''):240        """Verifies element identified by ``locator`` does not contain text ``expected``.241        ``message`` can be used to override the default error message.242        See `Element Should Contain Text` for more details.243        """244        self._info("Verifying element '%s' does not contain text '%s'."245                   % (locator, expected))246        actual = self._get_text(locator)247        if expected in actual:248            if not message:249                message = "Element '%s' should not contain text '%s' but " \250                          "it did." % (locator, expected)251            raise AssertionError(message)252    def element_text_should_be(self, locator, expected, message=''):253        """Verifies element identified by ``locator`` exactly contains text ``expected``.254        In contrast to `Element Should Contain Text`, this keyword does not try255        a substring match but an exact match on the element identified by ``locator``.256        ``message`` can be used to override the default error message.257        New in AppiumLibrary 1.4.258        """259        self._info("Verifying element '%s' contains exactly text '%s'."260                    % (locator, expected))261        element = self._element_find(locator, True, True)262        actual = element.text263        if expected != actual:264            if not message:265                message = "The text of element '%s' should have been '%s' but "\266                          "in fact it was '%s'." % (locator, expected, actual)267            raise AssertionError(message)268    def get_webelement(self, locator):269        """Returns the first [http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement|WebElement] object matching ``locator``.270        Example:271        | ${element}     | Get Webelement | id=my_element |272        | Click Element  | ${element}     |               |273        New in AppiumLibrary 1.4.274        """275        return self._element_find(locator, True, True)276    def get_webelements(self, locator):277        """Returns list of [http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement|WebElement] objects matching ``locator``.278        Example:279        | @{elements}    | Get Webelements | id=my_element |280        | Click Element  | @{elements}[2]  |               |281        This keyword was changed in AppiumLibrary 1.4 in following ways:282        - Name is changed from `Get Elements` to current one.283        - Deprecated argument ``fail_on_error``, use `Run Keyword and Ignore Error` if necessary.284        New in AppiumLibrary 1.4.285        """286        return self._element_find(locator, False, True)287    def get_element_attribute(self, locator, attribute):288        """Get element attribute using given attribute: name, value,...289        Examples:290        | Get Element Attribute | locator | name |291        | Get Element Attribute | locator | value |292        """293        294        if isinstance(locator, WebElement):295            try:296                attr_val = locator.get_attribute(attribute)297                self._info("Element '%s' attribute '%s' value '%s' " % (locator, attribute, attr_val))298                return attr_val299            except:300                raise AssertionError("Attribute '%s' is not valid for element '%s'" % (attribute, locator))301        else:302            elements = self._element_find(locator, False, True)303            ele_len = len(elements)304            if ele_len == 0:305                raise AssertionError("Element '%s' could not be found" % locator)306            elif ele_len > 1:307                self._info("CAUTION: '%s' matched %s elements - using the first element only" % (locator, len(elements)))308            try:309                attr_val = elements[0].get_attribute(attribute)310                self._info("Element '%s' attribute '%s' value '%s' " % (locator, attribute, attr_val))311                return attr_val312            except:313                raise AssertionError("Attribute '%s' is not valid for element '%s'" % (attribute, locator))314    def get_element_location(self, locator):315        """Get element location316        Key attributes for arbitrary elements are `id` and `name`. See317        `introduction` for details about locating elements.318        """319        element = self._element_find(locator, True, True)320        element_location = element.location321        self._info("Element '%s' location: %s " % (locator, element_location))322        return element_location323    324    def get_element_size(self, locator):325        """Get element size326        Key attributes for arbitrary elements are `id` and `name`. See327        `introduction` for details about locating elements.328        """329        element = self._element_find(locator, True, True)330        element_size = element.size331        self._info("Element '%s' size: %s " % (locator, element_size))332        return element_size333    def get_text(self, locator):334        """Get element text (for hybrid and mobile browser use `xpath` locator, others might cause problem)335        Example:336        | ${text} | Get Text | //*[contains(@text,'foo')] |337        New in AppiumLibrary 1.4.338        """339        text = self._get_text(locator)340        self._info("Element '%s' text is '%s' " % (locator, text))341        return text342    def get_matching_xpath_count(self, xpath):343        """Returns number of elements matching ``xpath``344        One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.345        | *Correct:* |346        | ${count}  | Get Matching Xpath Count | //android.view.View[@text='Test'] |347        | Incorrect:  |348        | ${count}  | Get Matching Xpath Count | xpath=//android.view.View[@text='Test'] |349        If you wish to assert the number of matching elements, use350        `Xpath Should Match X Times`.351        New in AppiumLibrary 1.4.352        """353        count = len(self._element_find("xpath=" + xpath, False, False))354        return str(count)355    def xpath_should_match_x_times(self, xpath, count, error=None, loglevel='INFO'):356        """Verifies that the page contains the given number of elements located by the given ``xpath``.357        One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.358        | *Correct:* |359        | Xpath Should Match X Times | //android.view.View[@text='Test'] | 1 |360        | Incorrect: |361        | Xpath Should Match X Times | xpath=//android.view.View[@text='Test'] | 1 |362        ``error`` can be used to override the default error message.363        See `Log Source` for explanation about ``loglevel`` argument.364        New in AppiumLibrary 1.4.365        """366        actual_xpath_count = len(self._element_find("xpath=" + xpath, False, False))367        if int(actual_xpath_count) != int(count):368            if not error:369                error = "Xpath %s should have matched %s times but matched %s times"\370                            %(xpath, count, actual_xpath_count)371            self.log_source(loglevel)372            raise AssertionError(error)373        self._info("Current page contains %s elements matching '%s'."374                   % (actual_xpath_count, xpath))375    # Private376    def _is_index(self, index_or_name):377        if index_or_name.startswith('index='):378            return True379        else:380            return False381    def _click_element_by_name(self, name):382        driver = self._current_application()383        try:384            element = driver.find_element_by_name(name)385        except Exception as e:386            raise e387        try:388            element.click()389        except Exception as e:390            raise 'Cannot click the element with name "%s"' % name391    def _find_elements_by_class_name(self, class_name):392        driver = self._current_application()393        elements = driver.find_elements_by_class_name(class_name)394        return elements395    def _find_element_by_class_name(self, class_name, index_or_name):396        elements = self._find_elements_by_class_name(class_name)397        if self._is_index(index_or_name):398            try:399                index = int(index_or_name.split('=')[-1])400                element = elements[index]401            except (IndexError, TypeError):402                raise 'Cannot find the element with index "%s"' % index_or_name403        else:404            found = False405            for element in elements:406                self._info("'%s'." % element.text)407                if element.text == index_or_name:408                    found = True409                    break410            if not found:411                raise 'Cannot find the element with name "%s"' % index_or_name412        return element413    def _get_class(self, platform_class_dict):414        return platform_class_dict.get(self._get_platform())415    def _is_support_platform(self, platform_class_dict):416        return platform_class_dict.has_key(self._get_platform())417    def _click_element_by_class_name(self, class_name, index_or_name):418        element = self._find_element_by_class_name(class_name, index_or_name)419        self._info("Clicking element '%s'." % element.text)420        try:421            element.click()422        except Exception as e:423            raise 'Cannot click the %s element "%s"' % (class_name, index_or_name)424    def _element_clear_text_by_locator(self, locator):425        try:426            element = self._element_find(locator, True, True)427            element.clear()428        except Exception as e:429            raise e430    def _element_input_text_by_locator(self, locator, text):431        try:432            element = self._element_find(locator, True, True)433            element.send_keys(text)434        except Exception as e:435            raise e436    def _element_input_text_by_class_name(self, class_name, index_or_name, text):437        try:438            element = self._find_element_by_class_name(class_name, index_or_name)439        except Exception as e:440            raise e441        self._info("input text in element as '%s'." % element.text)442        try:443            element.send_keys(text)444        except Exception as e:445            raise 'Cannot input text "%s" for the %s element "%s"' % (text, class_name, index_or_name)446    def _element_input_value_by_locator(self, locator, text):447        try:448            element = self._element_find(locator, True, True)449            element.set_value(text)450        except Exception as e:451            raise e452    def _element_find(self, locator, first_only, required, tag=None):453        application = self._current_application()454        if isstr(locator):455            # Normalize any unicode as explained here, http://appium.io/slate/en/master/?javascript#multi-lingual-support456            if self._get_platform() == 'ios':457                _locator = normalize('NFD', locator)458            else:459                _locator = locator460            elements = self._element_finder.find(application, _locator, tag)461            if required and len(elements) == 0:462                raise ValueError("Element locator '" + locator + "' did not match any elements.")463            if first_only:464                if len(elements) == 0: return None465                return elements[0]466        elif isinstance(locator, WebElement):467            elements = locator468        # do some other stuff here like deal with list of webelements469        # ... or raise locator/element specific error if required470        return elements471    def _get_text(self, locator):472        element = self._element_find(locator, True, True)473        if element is not None:474            return element.text475        return None476    def _is_text_present(self, text):477        text_norm = normalize('NFD', text)478        source_norm = normalize('NFD', self.get_source())479        return text_norm in source_norm480    def _is_element_present(self, locator):481        application = self._current_application()482        elements = self._element_finder.find(application, locator, None)483        return len(elements) > 0484        485    def _is_visible(self, locator):486        element = self._element_find(locator, True, False)487        if element is not None:488            return element.is_displayed()...SeleniumExtensions.py
Source:SeleniumExtensions.py  
...17        self._selenium2lib = BuiltIn().get_library_instance('Selenium2Library')18    def clickElementWithOnclickEvent(self, locator):19        """Finds element by locator and take its onclick-event action and runs it.20        """21        element = self._element_find(locator, True, True)22        js = element.getAttribute('onclick')23        self._selenium2lib.javaScript.executeJavascript(js)24    def indexForColumnByHeaderContent(self, headers, value):25        elements = self._element_find(headers, False, False)26        index = -127        for i, elem in enumerate(elements):28            if elem.text.strip() == value:29                index = i + 130                break31        return index32    def loopTableRowsAndMatchColumnContent(self, xpath_for_rows, index, value):33        elements = self._element_find(xpath_for_rows, False, False)34        for i, elem in enumerate(elements):35            xpath_for_column = xpath_for_rows + "[%s]//td[%s]" % (i + 1, index)36            if value.lower() in self._element_find(xpath_for_column, True, True).text.lower():37                break38        else:39            BuiltIn().fail("Could not find %s from rows" % value)40    def rowNumberByColumnAndValue(self, xpath_for_rows, value):41        count = -142        elements = self._element_find(xpath_for_rows, False, False)43        for i, elem in enumerate(elements):44            if value in elem.text:45                count = i + 146                break47        else:48            BuiltIn().fail("Could not find %s from elements of given xpath" % value)49        return count50    def selectOptionByIndex(self, locator, index):51        element = self._element_find(locator, True, True)52        js = "document.getElementById('%s').selectedIndex='%s';" % (element.get_attribute('id'), index)53        self._selenium2lib.execute_javascript(js)54    def selectRandomOption(self, locator, start_index=1):55        element_id = self._element_find(locator, True, True).get_attribute('id')56        js = "return document.getElementById('%s').length;" % element_id57        length = self._selenium2lib.execute_javascript(js)58        index = random.randint(start_index, int(length) - start_index)59        js = "document.getElementById('%s').selectedIndex='%s';" % (element_id, index)60        self._selenium2lib.execute_javascript(js)61    def getRandomText(self, locator, exlude_titles_include=""):62        elements = self._element_find(locator, False, False)63        titles = []64        value = None65        try:66            for elem in elements:67                if not exlude_titles_include or len(68                        exlude_titles_include) > 0 and not exlude_titles_include in elem.text:69                    titles.append(elem.text)70                value = random.choice(titles)71        except IndexError:72            raise Exception("Can not find any titles from element" + locator)73        return value74    def setCkeEditorContent(self, locator, content):75        iframe = self._element_find(locator, True, True)76        self._selenium2lib._current_browser().switch_to_frame(iframe)77        body = self._selenium2lib._current_browser().find_element_by_tag_name('body')78        body.send_keys(content)79        self._selenium2lib._current_browser().switch_to_default_content()80    def ifPopupExistsWithTextThenClickButton(self, text, button='ok'):81        alertFound = False82        try:83            alert = self._alert()84            if alert:85                if alert.text == text:86                    alertFound = True87                    if button.lower() == 'cancel':88                        alert.dismiss()89                        print "Dismissed popup"90                    else:91                        alert.accept()92                        print "Accepted popup"93                else:94                    raise SeleniumExtensionsException("Text '%s' does not match to '%s'." % (alert.text, text))95        except NoAlertPresentException:96            print "No alert found"97        return alertFound98    def addRandomProductToCart(self):99        '''100        Add a random product to the cart in the CPQ view of Salesforce101        '''102        xpath = "//div[@class='slds-col cpq-items-container scroll']//div[@data='card']"103        js = "return document.evaluate(\"count({0})\", document, null, XPathResult.ANY_TYPE, null).numberValue;".format(xpath)104        count = self._selenium2lib.execute_javascript(js)105        i = random.randint(1,count)106        js = "return document.evaluate(\"{0}[{1}]//p[contains(@class,'product-name')]\", document, null, XPathResult.ANY_TYPE, null).iterateNext().innerText;".format(xpath, i)107        product_name = self._selenium2lib.execute_javascript(js)108        self._click("{0}[{1}]//button[contains(text(),'Add to Cart')]".format(xpath, i))109        return product_name110    def editTimeShouldBeWithin(self, within, modified):111        # within = time in seconds112        timestamp = modified.split(",")[-1].strip()113        now = datetime.datetime.now()114        timestamp = datetime.datetime.strptime(timestamp, "%d.%m.%Y %H:%M")115        return now-timestamp < datetime.timedelta(seconds=int(within))116    def catenateNonEmptyValues(self, *items):117        return " ".join(filter(lambda x: len(x)>0, items))118    def getOpportunityIframeXpath(self, oppo_name):119        xpath = "//li[.//span[contains(text(),'{0}')] and not(contains(@id,'navigatortab'))]".format(oppo_name)120        js = "return document.evaluate(\"{0}\", document, null, XPathResult.ANY_TYPE, null).iterateNext().id;".format(xpath)121        id = self._selenium2lib.execute_javascript(js)122        div_id = id.split("__")[1]123        xpath = "//div[@id='{0}']//iframe".format(div_id)124        js = "return document.evaluate(\"{0}\", document, null, XPathResult.ANY_TYPE, null).iterateNext();".format(xpath)125        iframe = self._selenium2lib.execute_javascript(js)126        return iframe127    @property128    def using_java(self):129        return "_element_find" not in dir(self._selenium2lib)130    def _element_find(self, locator, onlyFirst, required, tag=None):131        if self.using_java:132            elements = self._selenium2lib.runKeyword('elementsFind', [locator, onlyFirst, required, tag])133            if onlyFirst:134                return elements[0]135            return elements136        else:137            return self._selenium2lib._element_find(locator, onlyFirst, required, tag)138    def _click(self, locator):139        if self.using_java:140            self._selenium2lib.element.clickElement(locator)141        else:142            self._selenium2lib._element_find(locator, True, True).click()143    def _input(self, locator, value):144        if self.using_java:145            self._selenium2lib.formElement.inputText(locator, value)146        else:147            self._selenium2lib.input_text(locator, value)148    def _wait(self, locator, timeout, error):149        if self.using_java:150            self._selenium2lib.waiting.waitUntilElementIsVisible(locator, timeout, error)151        else:152            self._selenium2lib._wait_until(timeout, error, self._selenium2lib._is_element_present, locator)153    def _alert(self):154        if self.using_java:155            return self._selenium2lib.browserManagement.getCurrentWebDriver().switchTo().alert()156        else:...S2ExLibrary.py
Source:S2ExLibrary.py  
...10    def get_text_list_from_elements(self, locator, regex):11        """ Get the text from elements located by locator.12        This method is just for extract page numbers, and need to fix        13        """14        elements = self.seleniumlib._element_find(locator, False, False)15        pattern = re.compile(regex)16        text = []17        for element in elements:18            if re.match(pattern, element.get_attribute('id')) is not None:19                text.append(element.text)20        return text21    22    def get_site_number(self):23        """ Use module re to match site number in the text of 'mainFormTable' element24        """25        element = self.seleniumlib._element_find('id=mainFormTable', True, True)26        pattern = re.compile('\d{12}')27        source = element.text28        number = re.findall(pattern, source)[0]29        return number30    31    def element_should_match_x_times(self, locator, times, message=''):32        """ To verify how many times the element located by locator occurs33        """34        self._info("Verifying element '%s' match '%s' times."35                    % (locator, times))36        elements = []37        elements = self.seleniumlib._element_find(str(locator), False, False)38        if len(elements) != int(times):39            if not message:40                message = "Element '%s' should match '%s' times but "\41                          "match '%s' times." % (locator, times, len(elements))42            raise AssertionError(message)43        44    def get_count_of_variables(self, locator, regex):45        elements = self.seleniumlib._element_find(locator, False, False)46        pattern = re.compile(regex)47        count = 048        for element in elements:49            if re.match(pattern, element.get_attribute('id')) is not None:50                count += 151        return count52    53    def get_text_list_from_elements_By_Locator(self, locator):54        """ Get the text from elements located by locator.55        This method is just for extract page numbers, and need to fix        56        """57        elements = self.seleniumlib._element_find(locator, False, False)58        text = []59        for element in elements:60            if element.text.__len__() > 0:61                text.append(element.text)62        return text63    def get_id_list_by_locator(self, locator):64        """ Get the id from elements by locator.               65        """66        elements = self.seleniumlib._element_find(locator, False, False)67        idList = []68        for element in elements:69            idList.append(element.get_attribute('id'))70        return idList71		72    def click_element_by_no(self, no, locator):73        """ Get the elements defined by the locator.74        Return the element designated by the no.75        """76        elements = self.seleniumlib._element_find(locator, False, False)77        self.seleniumlib._info("There are '%s' elements in this page." % len(elements))78        no = int(no) - 179        elements[no].click()80        81    def select_all_checkboxes(self, locator):82        """ Select all the checkboxes with the same name.83        """84        elements = self.seleniumlib._element_find(locator, False, False, tag='input')85        if len(elements) > 0 :86            for element in elements:87                if not element.is_selected():88                    element.click()89    90    def radio_button_should_be_selected(self, locator):91        """ Check radio button whether is selected by id.92        """93        element = self.seleniumlib._element_find(locator, True, True, tag='input')94        return element.is_selected()95    96    def click_visible_element(self, locator, no):97        """ Click element which is visible.98        """99        elements = self.seleniumlib._element_find(locator, False, False)100        elements = [e for e in elements if e.is_displayed()]101        self.seleniumlib._info("There are '%s' elements in this page." % len(elements))102        no = int(no) - 1103        elements[no].click()104       105        106    def set_element_attr(self, locator, attr, value):107        """ Change element attribute by value.108        """109        element = self.seleniumlib._elemtn_find(locator, True, True)110        element.set_attribute(str(attr), str(value))111        112    def get_visible_element_value(self, locator, no):113        """ Get visible element value ordered by no.114        """115        elements = self.seleniumlib._element_find(locator, False, False)116        elements = [e for e in elements if e.is_displayed()]117        self.seleniumlib._info("There are '%s' elements in this page." % len(elements))118        no = int(no) - 1119        return elements[no].get_attribute('value') if elements[no] is not None else None120    121    def visible_element_value_should_be(self, locator, val, no):122        elements = self.seleniumlib._element_find(locator, False, False)123        elements = [e for e in elements if e.is_displayed()]124        self.seleniumlib._info("There are '%s' elements in this page." % len(elements))125        no = int(no) - 1126        actual_val = elements[no].get_attribute('value') if elements[no] is not None else None127        return str(actual_val) == (str(val))128     129    def get_label_value_by_text(self, locator, text):130        elements = self.seleniumlib._element_find(locator, True, True).find_elements_by_tag_name("option")131        for e in elements:132            if text in e.text:133                return e.get_attribute("value")134    def _parse_locator(self, locator):135        prefix = None136        criteria = locator137        if not locator.startswith('//'):138            locator_parts = locator.partition('=')139            if len(locator_parts[1]) > 0:140                prefix = locator_parts[0].strip().lower()141                criteria = locator_parts[2].strip()142        return (prefix, criteria)143    def select_label(self, locator, text):144        value = self.get_label_value_by_text(locator, text)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
