How to use slow_scroll_to method in SeleniumBase

Best Python code snippet using SeleniumBase

base_case.py

Source:base_case.py Github

copy

Full Screen

...311 ''' Fast scroll to destination '''312 element = self.wait_for_element_visible(313 selector, by=by, timeout=timeout)314 self._scroll_to_element(element)315 def slow_scroll_to(self, selector, by=By.CSS_SELECTOR,316 timeout=settings.SMALL_TIMEOUT):317 ''' Slow motion scroll to destination '''318 element = self.wait_for_element_visible(319 selector, by=by, timeout=timeout)320 self._slow_scroll_to_element(element)321 def scroll_click(self, selector, by=By.CSS_SELECTOR):322 self.scroll_to(selector, by=by)323 self.click(selector, by=by)324 def jquery_click(self, selector, by=By.CSS_SELECTOR):325 if selector.startswith('/') or selector.startswith('./'):326 by = By.XPATH327 selector = self.convert_to_css_selector(selector, by=by)328 self.wait_for_element_present(329 selector, by=by, timeout=settings.SMALL_TIMEOUT)330 if self.is_element_visible(selector, by=by):331 self._demo_mode_highlight_if_active(selector, by)332 # Only get the first match333 last_syllable = selector.split(' ')[-1]334 if ':' not in last_syllable:335 selector += ':first'336 click_script = """jQuery('%s')[0].click()""" % selector337 try:338 self.execute_script(click_script)339 except Exception:340 # The likely reason this fails is because: "jQuery is not defined"341 self.activate_jquery() # It's a good thing we can define it here342 self.execute_script(click_script)343 self._demo_mode_pause_if_active()344 def jq_format(self, code):345 return page_utils.jq_format(code)346 def get_domain_url(self, url):347 return page_utils.get_domain_url(url)348 def download_file(self, file_url, destination_folder=None):349 """ Downloads the file from the url to the destination folder.350 If no destination folder is specified, the default one is used. """351 if not destination_folder:352 destination_folder = constants.Files.DOWNLOADS_FOLDER353 page_utils._download_file_to(file_url, destination_folder)354 return True355 def save_file_as(self, file_url, new_file_name, destination_folder=None):356 """ Similar to self.download_file(), except that you get to rename the357 file being downloaded to whatever you want. """358 if not destination_folder:359 destination_folder = constants.Files.DOWNLOADS_FOLDER360 page_utils._download_file_to(361 file_url, destination_folder, new_file_name)362 return True363 def convert_xpath_to_css(self, xpath):364 return xpath_to_css.convert_xpath_to_css(xpath)365 def convert_to_css_selector(self, selector, by):366 """ This method converts a selector to a CSS_SELECTOR.367 jQuery commands require a CSS_SELECTOR for finding elements.368 This method should only be used for jQuery actions. """369 if by == By.CSS_SELECTOR:370 return selector371 elif by == By.ID:372 return '#%s' % selector373 elif by == By.CLASS_NAME:374 return '.%s' % selector375 elif by == By.NAME:376 return '[name="%s"]' % selector377 elif by == By.TAG_NAME:378 return selector379 elif by == By.XPATH:380 return self.convert_xpath_to_css(selector)381 elif by == By.LINK_TEXT:382 return 'a:contains("%s")' % selector383 elif by == By.PARTIAL_LINK_TEXT:384 return 'a:contains("%s")' % selector385 else:386 raise Exception(387 "Exception: Could not convert [%s](by=%s) to CSS_SELECTOR!" % (388 selector, by))389 def set_value(self, selector, new_value, by=By.CSS_SELECTOR,390 timeout=settings.SMALL_TIMEOUT):391 """ This method uses jQuery to update a text field. """392 if selector.startswith('/') or selector.startswith('./'):393 by = By.XPATH394 selector = self.convert_to_css_selector(selector, by=by)395 self._demo_mode_highlight_if_active(selector, by)396 self.scroll_to(selector, by=by, timeout=timeout)397 value = json.dumps(new_value)398 # Only get the first match399 last_syllable = selector.split(' ')[-1]400 if ':' not in last_syllable:401 selector += ':first'402 set_value_script = """jQuery('%s').val(%s)""" % (selector, value)403 try:404 self.execute_script(set_value_script)405 except Exception:406 # The likely reason this fails is because: "jQuery is not defined"407 self.activate_jquery() # It's a good thing we can define it here408 self.execute_script(set_value_script)409 self._demo_mode_pause_if_active()410 def jquery_update_text_value(self, selector, new_value, by=By.CSS_SELECTOR,411 timeout=settings.SMALL_TIMEOUT):412 """ This method uses jQuery to update a text field.413 If the new_value string ends with the newline character,414 WebDriver will finish the call, which simulates pressing415 {Enter/Return} after the text is entered. """416 if selector.startswith('/') or selector.startswith('./'):417 by = By.XPATH418 element = self.wait_for_element_visible(419 selector, by=by, timeout=timeout)420 self._demo_mode_highlight_if_active(selector, by)421 self.scroll_to(selector, by=by)422 selector = self.convert_to_css_selector(selector, by=by)423 # Only get the first match424 last_syllable = selector.split(' ')[-1]425 if ':' not in last_syllable:426 selector += ':first'427 update_text_script = """jQuery('%s').val('%s')""" % (428 selector, self.jq_format(new_value))429 try:430 self.execute_script(update_text_script)431 except Exception:432 # The likely reason this fails is because: "jQuery is not defined"433 self.activate_jquery() # It's a good thing we can define it here434 self.execute_script(update_text_script)435 if new_value.endswith('\n'):436 element.send_keys('\n')437 self._demo_mode_pause_if_active()438 def jquery_update_text(self, selector, new_value, by=By.CSS_SELECTOR,439 timeout=settings.SMALL_TIMEOUT):440 """ The shorter version of jquery_update_text_value()441 (The longer version remains for backwards compatibility.) """442 self.jquery_update_text_value(443 selector, new_value, by=by, timeout=timeout)444 def hover_on_element(self, selector, by=By.CSS_SELECTOR):445 self.wait_for_element_visible(446 selector, by=by, timeout=settings.SMALL_TIMEOUT)447 self._demo_mode_highlight_if_active(selector, by)448 self.scroll_to(selector, by=by)449 time.sleep(0.05) # Settle down from scrolling before hovering450 return page_actions.hover_on_element(self.driver, selector)451 def hover_and_click(self, hover_selector, click_selector,452 hover_by=By.CSS_SELECTOR, click_by=By.CSS_SELECTOR,453 timeout=settings.SMALL_TIMEOUT):454 if hover_selector.startswith('/') or hover_selector.startswith('./'):455 hover_by = By.XPATH456 if click_selector.startswith('/') or click_selector.startswith('./'):457 click_by = By.XPATH458 self.wait_for_element_visible(459 hover_selector, by=hover_by, timeout=timeout)460 self._demo_mode_highlight_if_active(hover_selector, hover_by)461 self.scroll_to(hover_selector, by=hover_by)462 pre_action_url = self.driver.current_url463 element = page_actions.hover_and_click(464 self.driver, hover_selector, click_selector,465 hover_by, click_by, timeout)466 if self.demo_mode:467 if self.driver.current_url != pre_action_url:468 self._demo_mode_pause_if_active()469 else:470 self._demo_mode_pause_if_active(tiny=True)471 return element472 ############473 def wait_for_element_present(self, selector, by=By.CSS_SELECTOR,474 timeout=settings.LARGE_TIMEOUT):475 """ Waits for an element to appear in the HTML of a page.476 The element does not need be visible (it may be hidden). """477 if selector.startswith('/') or selector.startswith('./'):478 by = By.XPATH479 return page_actions.wait_for_element_present(480 self.driver, selector, by, timeout)481 def assert_element_present(self, selector, by=By.CSS_SELECTOR,482 timeout=settings.SMALL_TIMEOUT):483 """ Similar to wait_for_element_present(), but returns nothing.484 Waits for an element to appear in the HTML of a page.485 The element does not need be visible (it may be hidden).486 Returns True if successful. Default timeout = SMALL_TIMEOUT. """487 self.wait_for_element_present(selector, by=by, timeout=timeout)488 return True489 # For backwards compatibility, earlier method names of the next490 # four methods have remained even though they do the same thing,491 # with the exception of assert_*, which won't return the element,492 # but like the others, will raise an exception if the call fails.493 def wait_for_element_visible(self, selector, by=By.CSS_SELECTOR,494 timeout=settings.LARGE_TIMEOUT):495 """ Waits for an element to appear in the HTML of a page.496 The element must be visible (it cannot be hidden). """497 if selector.startswith('/') or selector.startswith('./'):498 by = By.XPATH499 return page_actions.wait_for_element_visible(500 self.driver, selector, by, timeout)501 def wait_for_element(self, selector, by=By.CSS_SELECTOR,502 timeout=settings.LARGE_TIMEOUT):503 """ The shorter version of wait_for_element_visible() """504 return self.wait_for_element_visible(selector, by=by, timeout=timeout)505 def find_element(self, selector, by=By.CSS_SELECTOR,506 timeout=settings.LARGE_TIMEOUT):507 """ Same as wait_for_element_visible() - returns the element """508 return self.wait_for_element_visible(selector, by=by, timeout=timeout)509 def assert_element(self, selector, by=By.CSS_SELECTOR,510 timeout=settings.SMALL_TIMEOUT):511 """ Similar to wait_for_element_visible(), but returns nothing.512 As above, will raise an exception if nothing can be found.513 Returns True if successful. Default timeout = SMALL_TIMEOUT. """514 self.wait_for_element_visible(selector, by=by, timeout=timeout)515 return True516 # For backwards compatibility, earlier method names of the next517 # four methods have remained even though they do the same thing,518 # with the exception of assert_*, which won't return the element,519 # but like the others, will raise an exception if the call fails.520 def wait_for_text_visible(self, text, selector, by=By.CSS_SELECTOR,521 timeout=settings.LARGE_TIMEOUT):522 if selector.startswith('/') or selector.startswith('./'):523 by = By.XPATH524 return page_actions.wait_for_text_visible(525 self.driver, text, selector, by, timeout)526 def wait_for_text(self, text, selector, by=By.CSS_SELECTOR,527 timeout=settings.LARGE_TIMEOUT):528 """ The shorter version of wait_for_text_visible() """529 return self.wait_for_text_visible(530 text, selector, by=by, timeout=timeout)531 def find_text(self, text, selector, by=By.CSS_SELECTOR,532 timeout=settings.LARGE_TIMEOUT):533 """ Same as wait_for_text_visible() - returns the element """534 return self.wait_for_text_visible(535 text, selector, by=by, timeout=timeout)536 def assert_text(self, text, selector, by=By.CSS_SELECTOR,537 timeout=settings.SMALL_TIMEOUT):538 """ Similar to wait_for_text_visible(), but returns nothing.539 As above, will raise an exception if nothing can be found.540 Returns True if successful. Default timeout = SMALL_TIMEOUT. """541 self.wait_for_text_visible(text, selector, by=by, timeout=timeout)542 return True543 # For backwards compatibility, earlier method names of the next544 # four methods have remained even though they do the same thing,545 # with the exception of assert_*, which won't return the element,546 # but like the others, will raise an exception if the call fails.547 def wait_for_link_text_visible(self, link_text,548 timeout=settings.LARGE_TIMEOUT):549 return self.wait_for_element_visible(550 link_text, by=By.LINK_TEXT, timeout=timeout)551 def wait_for_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT):552 """ The shorter version of wait_for_link_text_visible() """553 return self.wait_for_link_text_visible(link_text, timeout=timeout)554 def find_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT):555 """ Same as wait_for_link_text_visible() - returns the element """556 return self.wait_for_link_text_visible(link_text, timeout=timeout)557 def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT):558 """ Similar to wait_for_link_text_visible(), but returns nothing.559 As above, will raise an exception if nothing can be found.560 Returns True if successful. Default timeout = SMALL_TIMEOUT. """561 self.wait_for_link_text_visible(link_text, timeout=timeout)562 return True563 ############564 def wait_for_element_absent(self, selector, by=By.CSS_SELECTOR,565 timeout=settings.LARGE_TIMEOUT):566 """ Waits for an element to no longer appear in the HTML of a page.567 A hidden element still counts as appearing in the page HTML.568 If an element with "hidden" status is acceptable,569 use wait_for_element_not_visible() instead. """570 if selector.startswith('/') or selector.startswith('./'):571 by = By.XPATH572 return page_actions.wait_for_element_absent(573 self.driver, selector, by, timeout)574 def assert_element_absent(self, selector, by=By.CSS_SELECTOR,575 timeout=settings.SMALL_TIMEOUT):576 """ Similar to wait_for_element_absent() - returns nothing.577 As above, will raise an exception if the element stays present.578 Returns True if successful. Default timeout = SMALL_TIMEOUT. """579 self.wait_for_element_absent(selector, by=by, timeout=timeout)580 return True581 ############582 def wait_for_element_not_visible(self, selector, by=By.CSS_SELECTOR,583 timeout=settings.LARGE_TIMEOUT):584 """ Waits for an element to no longer be visible on a page.585 The element can be non-existant in the HTML or hidden on the page586 to qualify as not visible. """587 if selector.startswith('/') or selector.startswith('./'):588 by = By.XPATH589 return page_actions.wait_for_element_not_visible(590 self.driver, selector, by, timeout)591 def assert_element_not_visible(self, selector, by=By.CSS_SELECTOR,592 timeout=settings.SMALL_TIMEOUT):593 """ Similar to wait_for_element_not_visible() - returns nothing.594 As above, will raise an exception if the element stays visible.595 Returns True if successful. Default timeout = SMALL_TIMEOUT. """596 self.wait_for_element_not_visible(selector, by=by, timeout=timeout)597 return True598 ############599 def wait_for_ready_state_complete(self, timeout=settings.EXTREME_TIMEOUT):600 return page_actions.wait_for_ready_state_complete(self.driver, timeout)601 def wait_for_and_accept_alert(self, timeout=settings.LARGE_TIMEOUT):602 return page_actions.wait_for_and_accept_alert(self.driver, timeout)603 def wait_for_and_dismiss_alert(self, timeout=settings.LARGE_TIMEOUT):604 return page_actions.wait_for_and_dismiss_alert(self.driver, timeout)605 def wait_for_and_switch_to_alert(self, timeout=settings.LARGE_TIMEOUT):606 return page_actions.wait_for_and_switch_to_alert(self.driver, timeout)607 def save_screenshot(self, name, folder=None):608 return page_actions.save_screenshot(self.driver, name, folder)609 ############610 def _get_exception_message(self):611 """ This method extracts the message from an exception if there612 was an exception that occurred during the test, assuming613 that the exception was in a try/except block and not thrown. """614 exception_info = sys.exc_info()[1]615 if hasattr(exception_info, 'msg'):616 exc_message = exception_info.msg617 elif hasattr(exception_info, 'message'):618 exc_message = exception_info.message619 else:620 exc_message = '(Unknown Exception)'621 return exc_message622 def _package_check(self):623 current_url = self.driver.current_url624 message = self._get_exception_message()625 self.page_check_failures.append(626 "CHECK #%s: (%s)\n %s" % (627 self.page_check_count, current_url, message))628 def check_assert_element(self, selector, by=By.CSS_SELECTOR,629 timeout=settings.MINI_TIMEOUT):630 """ A non-terminating assertion for an element on a page.631 Any and all exceptions will be saved until the process_checks()632 method is called from inside a test, likely at the end of it. """633 self.page_check_count += 1634 try:635 self.wait_for_element_visible(selector, by=by, timeout=timeout)636 return True637 except Exception:638 self._package_check()639 return False640 def check_assert_text(self, text, selector, by=By.CSS_SELECTOR,641 timeout=settings.MINI_TIMEOUT):642 """ A non-terminating assertion for text from an element on a page.643 Any and all exceptions will be saved until the process_checks()644 method is called from inside a test, likely at the end of it. """645 self.page_check_count += 1646 try:647 self.wait_for_text_visible(text, selector, by=by, timeout=timeout)648 return True649 except Exception:650 self._package_check()651 return False652 def process_checks(self):653 """ To be used at the end of any test that uses checks, which are654 non-terminating verifications that will only raise an exception655 after this method is called. Useful for pages with multiple656 elements to be checked when you want to find as many failures657 as possible on a page before making fixes.658 Might be more useful if this method is called after processing659 all the checks for a single html page, otherwise the screenshot660 in the logs file won't match the location of the checks. """661 if self.page_check_failures:662 exception_output = ''663 exception_output += "\n*** FAILED CHECKS FOR: %s\n" % self.id()664 all_failing_checks = self.page_check_failures665 self.page_check_failures = []666 for tb in all_failing_checks:667 exception_output += "%s\n" % tb668 raise Exception(exception_output)669 ############670 def _demo_mode_pause_if_active(self, tiny=False):671 if self.demo_mode:672 if self.demo_sleep:673 wait_time = float(self.demo_sleep)674 else:675 wait_time = settings.DEFAULT_DEMO_MODE_TIMEOUT676 if not tiny:677 time.sleep(wait_time)678 else:679 time.sleep(wait_time/3.4)680 def _demo_mode_scroll_if_active(self, selector, by):681 if self.demo_mode:682 self.slow_scroll_to(selector, by=by)683 def _demo_mode_highlight_if_active(self, selector, by):684 if self.demo_mode:685 # Includes self.slow_scroll_to(selector, by=by) by default686 self.highlight(selector, by=by)687 def _scroll_to_element(self, element):688 element_location = element.location['y']689 element_location = element_location - 130690 if element_location < 0:691 element_location = 0692 scroll_script = "window.scrollTo(0, %s);" % element_location693 # The old jQuery scroll_script required by=By.CSS_SELECTOR694 # scroll_script = "jQuery('%s')[0].scrollIntoView()" % selector695 self.execute_script(scroll_script)696 self._demo_mode_pause_if_active(tiny=True)697 def _slow_scroll_to_element(self, element):698 scroll_position = self.execute_script("return window.scrollY;")699 element_location = element.location['y']...

Full Screen

Full Screen

demo_mode.py

Source:demo_mode.py Github

copy

Full Screen

...23 demo_mode = config.getoption("demo_mode", skip=True)24 if demo_mode:25 logger.debug('Demo node: slow scrolling to {}:"{}"', how.upper(), selector)26 test = getattr(config, "_webdriver_test")27 test.slow_scroll_to(how, selector)28def demo_mode_pause_if_active(tiny=False):29 config: "Config" = runtime_store[pytestconfig]30 demo_mode = config.getoption("demo_mode", skip=True)31 if demo_mode:32 logger.debug("Pausing demo mode ...")33 wait_time = settings.DEFAULT_DEMO_MODE_TIMEOUT34 if config.getoption("demo_sleep", False):35 wait_time = float(config.getoption("demo_sleep"))36 if not tiny:37 time.sleep(wait_time)38 else:39 time.sleep(wait_time / 3.4)40 elif config.getoption("slow_mode", None):41 logger.debug("Pausing slow mode ...")42 test = getattr(config, "_webdriver_test")43 getattr(test, "_slow_mode_pause_if_active")()44@validate_arguments45def demo_mode_highlight_if_active(46 driver: WebDriver,47 how: SeleniumBy,48 selector: str = Field(default="", strict=True, min_length=1),49) -> None:50 config: "Config" = runtime_store[pytestconfig]51 demo_mode = config.getoption("demo_mode", skip=True)52 slow_mode = config.getoption("slow_mode", False)53 test = getattr(config, "_webdriver_test")54 if demo_mode:55 # Includes self.slow_scroll_to(selector, by=by) by default56 test.highlight(how, selector)57 elif slow_mode:58 # Just do the slow scroll part of the highlight() method59 time.sleep(0.08)60 from .element_actions import wait_for_element_visible61 element = wait_for_element_visible(how, selector, timeout=constants.SMALL_TIMEOUT)62 try:63 scroll_distance = get_scroll_distance_to_element(driver, element)64 if abs(scroll_distance) > settings.SSMD:65 from .js_utils import jquery_slow_scroll_to66 jquery_slow_scroll_to(driver, how, selector)67 else:68 from .js_utils import slow_scroll_to_element69 slow_scroll_to_element(element)70 except StaleElementReferenceException | ElementNotInteractableException:71 test.wait_for_ready_state_complete()72 time.sleep(0.12)73 element = test.wait_for_element_visible(how, selector, constants.SMALL_TIMEOUT)74 from .js_utils import slow_scroll_to_element75 slow_scroll_to_element(element)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run SeleniumBase automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful