Best Python code snippet using lettuce_webdriver_python
webdriver.py
Source:webdriver.py  
...229    """230    form = world.browser.find_element_by_xpath(str('//form'))231    form.submit()232@step(r'I submit the form with id "([^"]*)"')233def submit_form_id(step, id):234    """235    Submit the form having given id.236    """237    form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id)))238    form.submit()239@step(r'I submit the form with action "([^"]*)"')240def submit_form_action(step, url):241    """242    Submit the form having given action URL.243    """244    form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' %245                                                   url))246    form.submit()247# Checkboxes...yad2.py
Source:yad2.py  
1# coding=utf-82import logging3from selenium import webdriver4from contextlib import contextmanager5from sys import platform6class Yad2Error(Exception):7    pass8class Yad2:9    USERNAME_TEXTBOX_ID = 'userName'10    PASSWORD_TEXTBOX_ID = 'password'11    SUBMIT_FORM_ID = 'submitLogonForm'12    LOGOUT_BUTTON_CLASS = 'logout'13    LOGIN_URL = 'https://my.yad2.co.il/login.php'14    PERSONAL_AREA_URL = 'https://my.yad2.co.il//newOrder/index.php?action=personalAreaIndex'15    AD_DETAILS_MAX_LEN = 6416    def __init__(self, executable_path=None):17        options = webdriver.ChromeOptions()18        if platform == "linux" or platform == "linux2":19            options.binary_location = '/usr/bin/google-chrome-stable'20            options.add_argument('headless')21        chrome_kwargs = {'options': options}22        if executable_path is not None:23            chrome_kwargs['executable_path'] = executable_path24        self._driver = webdriver.Chrome(**chrome_kwargs)25        self._create_logger('yad2.log')26    def _create_logger(self, logfile):27        logger_handler = logging.FileHandler(logfile, encoding='utf8')28        logger_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')29        logger_handler.setFormatter(logger_formatter)30        self._logger = logging.getLogger(__name__)31        self._logger.setLevel(logging.DEBUG)32        self._logger.addHandler(logger_handler)33    @contextmanager34    def login(self, email, password):35        self._logger.info('Logging in to %s', email)36        self._login(email, password)37        self._logger.info('Logged in to %s', email)38        try:39            yield40        finally:41            self._logger.info('Logging out from %s', email)42            self._logout()43            self._logger.info('Logged out from %s', email)44    def _login(self, email, password):45        self._driver.get(Yad2.LOGIN_URL)46        username_textbox = self._driver.find_element_by_id(Yad2.USERNAME_TEXTBOX_ID)47        password_textbox = self._driver.find_element_by_id(Yad2.PASSWORD_TEXTBOX_ID)48        submit_button = self._driver.find_element_by_id(Yad2.SUBMIT_FORM_ID)49        username_textbox.send_keys(email)50        password_textbox.send_keys(password)51        submit_button.click()52        if self._driver.current_url != Yad2.PERSONAL_AREA_URL:53            self._raise_error('Login failed for {}'.format(email))54    def _logout(self):55        logout_button = self._driver.find_element_by_class_name(Yad2.LOGOUT_BUTTON_CLASS)56        logout_button.click()57        with self.enter_alert() as alert:58            alert.accept()59    def iterate_categories(self):60        """61        Iterates over all the available categories.62        Every available category in entered and its name is yielded.63        Note:64        Every time a category is selected the page changes - this invalidates all the object that represent65        elements in the page, therefor every time a category is selected all the categories should be66        queried again and iterated until all the categories where visited.67        """68        visited_categories = list()69        iterated_all_categories = False70        while not iterated_all_categories:71            # Obtain the list of categories72            link_containers = self._driver.find_elements_by_class_name('links_container')73            if len(link_containers) != 1:74                self._raise_error('Failed to find a single link container')75            for category_link in link_containers.pop().find_elements_by_class_name('catSubcatTitle'):76                if category_link.text not in visited_categories:77                    visited_categories.append(category_link.text)78                    # Clicking the category will direct us to its page79                    category_text = category_link.text80                    category_link.click()81                    yield category_text82                    # After clicking a category we need to obtain the reloaded category list83                    break84            else:85                iterated_all_categories = True86    def iterate_ads(self):87        return (ad for ad in self._driver.find_elements_by_class_name('item'))88    def bounce_all_ads(self):89        for category_text in self.iterate_categories():90            self._logger.info(u'Opened category: ' + category_text)91            for ad in self.iterate_ads():92                ad_status = ad.find_element_by_class_name('status_wrapper')93                if ad_status.text == u'×¤× ×ª××§×£':94                    ad_text = ad.find_element_by_class_name('textArea').text95                    self._logger.info('The following ad is out dated: %s', ad_text)96                    continue97                with self.enter_ad(ad):98                    ad_details = self._driver.find_element_by_class_name('details_area').text.strip().replace('\n', ' ')99                    ad_details = (100                        ad_details[:Yad2.AD_DETAILS_MAX_LEN] if len(ad_details) <= Yad2.AD_DETAILS_MAX_LEN else101                        ad_details[:Yad2.AD_DETAILS_MAX_LEN-3] + '...'102                    )103                    self._logger.info('Handling ad: %s', ad_details)104                    bounce_button = self._driver.find_element_by_id('bounceRatingOrderBtn')105                    if bounce_button.value_of_css_property('background').startswith(u'rgb(204, 204, 204)'):106                        self._logger.info('Bounce button is disabled')107                    else:108                        bounce_button.click()109                        self._logger.info('Bounced Ad!')110    @contextmanager111    def enter_ad(self, ad):112        # Open the ad113        ad.click()114        ad_content_frames = self._driver.find_elements_by_tag_name('iframe')115        # Find the iframe of the ad by ad's orderid116        ad_content_frames = filter(117            lambda e: e.get_attribute('src').endswith(u'OrderID=' + ad.get_attribute('data-orderid')),118            ad_content_frames119        )120        ad_content_frames = list(ad_content_frames)121        if len(ad_content_frames) != 1:122            self._raise_error('Failed to find a single iframe')123        try:124            with self.enter_iframe(ad_content_frames.pop()):125                yield126        except Exception as exc:127            self._logger.error("Failed to handle ad: %s", str(exc))128        finally:129            # Close the ad130            ad.click()131    @contextmanager132    def enter_iframe(self, iframe):133        self._driver.switch_to.frame(iframe)134        try:135            yield136        finally:137            self._driver.switch_to.default_content()138    @contextmanager139    def enter_alert(self):140        try:141            yield self._driver.switch_to.alert142        finally:143            self._driver.switch_to.default_content()144    def get_screenshot_as_file(self, filename):145        self._driver.get_screenshot_as_file(filename)146    def _raise_error(self, error_message):147        self._logger.error(error_message)...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!!
