How to use slow_scroll_to_element method in SeleniumBase

Best Python code snippet using SeleniumBase

webdrivertest.py

Source:webdrivertest.py Github

copy

Full Screen

...171 # scroll_distance = get_scroll_distance_to_element(self.driver, element)172 # if abs(scroll_distance) > settings.SSMD:173 # jquery_slow_scroll_to(how, selector)174 # else:175 # self.__slow_scroll_to_element(element)176 # except (StaleElementReferenceException, ElementNotInteractableException):177 # self.wait_for_ready_state_complete()178 # time.sleep(0.12)179 # element = self.wait_for_element_visible(how, selector, constants.SMALL_TIMEOUT)180 # self.__slow_scroll_to_element(element)181 # time.sleep(0.12)182 def __quit_all_drivers(self):183 shared_drv = runtime_store.get(shared_driver, None)184 if self._reuse_session and shared_drv:185 if len(self._drivers_list) > 0:186 if self._drivers_list[0] != shared_drv:187 if shared_drv in self._drivers_list:188 self._drivers_list.remove(shared_drv)189 self._drivers_list.insert(0, shared_drv)190 self._default_driver = self._drivers_list[0]191 self.switch_to_default_driver()192 if len(self._drivers_list) > 1:193 self._drivers_list = self._drivers_list[1:]194 else:195 self._drivers_list = []196 # Close all open browser windows197 self._drivers_list.reverse() # Last In, First Out198 for driver in self._drivers_list:199 try:200 self.__generate_logs(driver)201 driver.quit()202 except AttributeError:203 pass204 except WebDriverException:205 pass206 self.driver = None207 self._default_driver = None208 self._drivers_list = []209 def __is_in_frame(self):210 return is_in_frame(self.driver)211 def is_chromium(self):212 """Return True if the browser is Chrome, Edge, or Opera."""213 self.__check_scope__()214 chromium = False215 browser_name = self.driver.capabilities["browserName"]216 if browser_name.lower() in ("chrome", "edge", "msedge", "opera"):217 chromium = True218 return chromium219 def ad_block(self):220 """Block ads that appear on the current web page."""221 ...222 def set_time_limit(self, time_limit: OptionalInt = None):223 self.__check_scope__()224 super(WebDriverTest, self).set_time_limit(time_limit)225 def sleep(self, seconds):226 self.__check_scope__()227 limit = runtime_store.get(time_limit, None)228 if limit:229 time.sleep(seconds)230 elif seconds < 0.4:231 check_if_time_limit_exceeded()232 time.sleep(seconds)233 check_if_time_limit_exceeded()234 else:235 start_ms = time.time() * 1000.0236 stop_ms = start_ms + (seconds * 1000.0)237 for x in range(int(seconds * 5)):238 check_if_time_limit_exceeded()239 now_ms = time.time() * 1000.0240 if now_ms >= stop_ms:241 break242 time.sleep(0.2)243 def teardown(self) -> None:244 self.__quit_all_drivers()245 super().teardown()246 def setup(self) -> None:247 super(WebDriverTest, self).setup()248 if self._called_setup:249 return250 # self.addfinalizer(self._generate_driver_logs)251 self._called_setup = True252 self._called_teardown = False253 # self.slow_mode = self.config.getoption("slow_mode", False)254 # self.demo_mode = self.config.getoption("demo_mode", False)255 # self.demo_sleep = sb_config.demo_sleep256 # self.highlights = sb_config.highlights257 # self.time_limit = sb_config._time_limit258 # sb_config.time_limit = sb_config._time_limit # Reset between tests259 # self.environment = sb_config.environment260 # self.env = self.environment # Add a shortened version261 # self.with_selenium = sb_config.with_selenium # Should be True262 # self.headless = self.config.getoption("headless", False)263 self._headless_active = False264 # self.headed = self.config.getoption("headed", False)265 # self.xvfb = self.config.getoption("xvfb", False)266 # self.interval = sb_config.interval267 # self.start_page = sb_config.start_page268 # self.with_testing_base = sb_config.with_testing_base269 # self.with_basic_test_info = sb_config.with_basic_test_info270 # self.with_screen_shots = sb_config.with_screen_shots271 # self.with_page_source = sb_config.with_page_source272 # self.with_db_reporting = sb_config.with_db_reporting273 # self.with_s3_logging = sb_config.with_s3_logging274 # self.protocol = sb_config.protocol275 # self.servername = sb_config.servername276 # self.port = sb_config.port277 # self.proxy_string = sb_config.proxy_string278 # self.proxy_bypass_list = sb_config.proxy_bypass_list279 # self.user_agent = sb_config.user_agent280 # self.mobile_emulator = sb_config.mobile_emulator281 # self.device_metrics = sb_config.device_metrics282 # self.cap_file = sb_config.cap_file283 # self.cap_string = sb_config.cap_string284 # self.settings_file = sb_config.settings_file285 # self.database_env = sb_config.database_env286 # self.message_duration = sb_config.message_duration287 # self.js_checking_on = sb_config.js_checking_on288 # self.ad_block_on = sb_config.ad_block_on289 # self.block_images = sb_config.block_images290 # self.chromium_arg = sb_config.chromium_arg291 # self.firefox_arg = sb_config.firefox_arg292 # self.firefox_pref = sb_config.firefox_pref293 # self.verify_delay = sb_config.verify_delay294 # self.disable_csp = sb_config.disable_csp295 # self.disable_ws = sb_config.disable_ws296 # self.enable_ws = sb_config.enable_ws297 if not self.config.getoption("disable_ws", False):298 self._enable_ws = True299 # self.swiftshader = sb_config.swiftshader300 # self.user_data_dir = sb_config.user_data_dir301 # self.extension_zip = sb_config.extension_zip302 # self.extension_dir = sb_config.extension_dir303 # self.external_pdf = sb_config.external_pdf304 # self.maximize_option = sb_config.maximize_option305 # self.save_screenshot_after_test = sb_config.save_screenshot306 # self.visual_baseline = sb_config.visual_baseline307 # self.timeout_multiplier = sb_config.timeout_multiplier308 # self.pytest_html_report = sb_config.pytest_html_report309 # self.report_on = False310 # if self.pytest_html_report:311 # self.report_on = True312 if self.config.getoption("servername", None):313 if self.config.getoption("servername") != "localhost":314 self._use_grid = True315 if self.config.getoption("with_db_reporting", False):316 pass317 headless = self.config.getoption("headless", False)318 xvfb = self.config.getoption("xvfb", False)319 if headless or xvfb:320 ...321 from sel4.core.runtime import start_time_ms, timeout_changed322 if runtime_store.get(timeout_changed, False):323 ...324 if self.config.getoption("device_metrics", False):325 ...326 if self.config.getoption("mobile_emulator", False):327 ...328 if self.config.getoption("dashboard", False):329 ...330 from sel4.core.runtime import shared_driver331 has_url = False332 if self._reuse_session:333 if runtime_store.get(shared_driver, None):334 try:335 self._default_driver = runtime_store.get(shared_driver, None)336 self.driver: WebDriver = runtime_store.get(shared_driver, None)337 self._drivers_list = [self.driver]338 url, httpx_url = self.get_current_url()339 if url is not None:340 has_url = True341 if len(self.driver.window_handles) > 1:342 while len(self.driver.window_handles) > 1:343 self.switch_to_window(len(self.driver.window_handles) - 1)344 self.driver.close()345 self.switch_to_window(0)346 if self.config.getoption("crumbs", False):347 self.driver.delete_all_cookies()348 except WebDriverException:349 pass350 if self._reuse_session and runtime_store.get(shared_driver, None) and has_url:351 start_page = False352 if self.config.getoption("start_page", None):353 HttpUrl.validate(self.config.getoption("start_page"))354 start_page = True355 self.open(self.config.getoption("start_page"))356 else:357 try:358 browser_launcher = WebDriverBrowserLauncher(359 browser_name=self.config.getini("browser_name"),360 headless=self.config.getoption("headless"),361 enable_sync=self.config.getoption("enable_sync", False),362 use_grid=self._use_grid,363 block_images=self.config.getoption("block_images", False),364 external_pdf=self.config.getoption("external_pdf", False),365 mobile_emulator=self.config.getoption("mobile_emulator", False),366 user_agent=self.config.getoption("user_agent", None),367 proxy_auth=self.config.getoption("proxy_auth", None),368 disable_csp=self.config.getoption("disable_csp", False),369 ad_block_on=self.config.getoption("ad_block_on", False),370 devtools=self.config.getoption("devtools", False),371 incognito=self.config.getoption("incognito", False),372 guest_mode=self.config.getoption("guest_mode", False),373 extension_zip=self.config.getoption("extension_zip", []),374 extension_dir=self.config.getoption("extension_dir", None),375 user_data_dir=self.config.getoption("user_data_dir", None),376 servername=self.config.getoption("servername", None),377 use_auto_ext=self.config.getoption("use_auto_ext", False),378 proxy_string=self.config.getoption("proxy_string", None),379 enable_ws=self.config.getoption("enable_ws", False),380 remote_debug=self.config.getoption("remote_debug", False),381 swiftshader=self.config.getoption("swiftshader", False),382 chromium_arg=self.config.getoption("chromium_arg", []),383 )384 except ValidationError as e:385 logger.exception("Failed to validate WebDriverBrowserLauncher", e)386 raise e387 self.driver = self.get_new_driver(browser_launcher, switch_to=True)388 self._default_driver = self.driver389 if self._reuse_session:390 runtime_store[shared_driver] = self.driver391 if self.config.getini("browser_name") in ["firefox", "safari"]:392 self.config.option.mobile_emulator = False393 self.set_time_limit(self.config.getoption("time_limit", None))394 runtime_store[start_time_ms] = int(time.time() * 1000.0)395 if not self._start_time_ms:396 # Call this once in case of multiple setUp() calls in the same test397 self._start_time_ms = runtime_store[start_time_ms]398 # region WebDriver Actions399 def get_page_source(self) -> str:400 self.wait_for_ready_state_complete()401 logger.debug("Returning current page source")402 return self.driver.page_source403 def get_current_url(self) -> str:404 self.__check_scope__()405 current_url = self.driver.current_url406 logger.debug("Gets the current page url -> {}", current_url)407 return current_url408 def open(self, url: str) -> None:409 """410 Navigates the current browser window to the specified page.411 :param url: the url to navigate to412 """413 self.__check_scope__()414 self.__check_browser__()415 pre_action_url = self.driver.current_url416 try:417 _method = "selenium.webdriver.chrome.webdriver.get()"418 logger.debug("Navigate to {url} using [inspect.class]{method}[/]", url=url, method=_method)419 open_url(self.driver, url, tries=2)420 except WebDriverException as e:421 # TODO: ExceptionFormatter422 logger.exception("Could not open url: {url}", url=url)423 e.__logged__ = True424 raise e425 if self.driver.current_url == pre_action_url and pre_action_url != url:426 time.sleep(0.1)427 if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:428 self.wait_for_ready_state_complete()429 demo_mode_pause_if_active()430 def open_new_window(self, switch_to=True):431 """ Opens a new browser tab/window and switches to it by default. """432 logger.debug("Open a new browser window and switch to it -> {}", switch_to)433 self.__check_scope__()434 self.driver.execute_script("window.open('');")435 time.sleep(0.01)436 if switch_to:437 self.switch_to_newest_window()438 time.sleep(0.01)439 if self.driver.capabilities.get("browserName") == "safari":440 self.wait_for_ready_state_complete()441 @validate_arguments442 def switch_to_window(self, window: int | str, timeout: OptionalInt) -> None:443 """444 Switches control of the browser to the specified window.445 :param window: The window index or the window name446 :param timeout: optiona timeout447 """448 logger.debug(" Switches control of the browser to the specified window -> ", window)449 self.__check_scope__()450 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)451 switch_to_window(self.driver, window, timeout)452 def switch_to_default_window(self) -> None:453 self.switch_to_window(0)454 def switch_to_default_driver(self):455 """Sets driver to the default/original driver."""456 self.__check_scope__()457 self.driver = self._default_driver458 if self.driver in self.__driver_browser_map:459 getattr(self.config, "_inicache")["browser_name"] = self.__driver_browser_map[self.driver]460 self.bring_active_window_to_front()461 def switch_to_newest_window(self):462 self.switch_to_window(len(self.driver.window_handles) - 1)463 def get_new_driver(self, launcher_data: WebDriverBrowserLauncher, switch_to=True):464 self.__check_scope__()465 browser = self.config.getini("browser_name")466 if browser == "remote" and self.config.getoption("servername", "") == "localhost":467 raise RuntimeError(468 'Cannot use "remote" browser driver on localhost!'469 " Did you mean to connect to a remote Grid server"470 " such as BrowserStack or Sauce Labs? In that"471 ' case, you must specify the "server" and "port"'472 " parameters on the command line! "473 )474 cap_file = self.config.getoption("cap_file", None)475 cap_string = self.config.getoption("cap_string", None)476 if browser == "remote" and not (cap_file or cap_string):477 browserstack_ref = "https://browserstack.com/automate/capabilities"478 sauce_labs_ref = "https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/"479 raise RuntimeError(480 "Need to specify a desired capabilities file when "481 'using "--browser remote". Add "--cap_file FILE". '482 "File should be in the Python format"483 "%s OR "484 "%s "485 "See SeleniumBase/examples/sample_cap_file_BS.py "486 "and SeleniumBase/examples/sample_cap_file_SL.py" % (browserstack_ref, sauce_labs_ref)487 )488 new_driver = get_driver(launcher_data)489 self._drivers_list.append(new_driver)490 self.__driver_browser_map[new_driver] = launcher_data.browser_name491 if switch_to:492 self.driver = new_driver493 browser_name = launcher_data.browser_name494 # TODO: change ini value495 if self.config.getoption("headless", False) or self.config.getoption("xvfb", False):496 width = settings.HEADLESS_START_WIDTH497 height = settings.HEADLESS_START_HEIGH498 self.driver.set_window_size(width, height)499 self.wait_for_ready_state_complete()500 else:501 browser_name = self.driver.capabilities.get("browserName").lower()502 if browser_name == "chrome" or browser_name == "edge":503 width = settings.CHROME_START_WIDTH504 height = settings.CHROME_START_HEIGHT505 if self.config.getoption("maximize_option", False):506 self.driver.maximize_window()507 elif self.config.getoption("fullscreen_option", False):508 self.driver.fullscreen_window()509 else:510 self.driver.set_window_size(width, height)511 self.wait_for_ready_state_complete()512 elif browser_name == "firefox":513 width = settings.CHROME_START_WIDTH514 if self.config.getoption("maximize_option", False):515 self.driver.maximize_window()516 else:517 self.driver.set_window_size(width, 720)518 self.wait_for_ready_state_complete()519 elif browser_name == "safari":520 width = settings.CHROME_START_WIDTH521 if self.config.getoption("maximize_option", False):522 self.driver.maximize_window()523 self.wait_for_ready_state_complete()524 else:525 self.driver.set_window_rect(10, 30, width, 630)526 if self.config.getoption("start_page", None):527 self.open(self.config.getoption("start_page"))528 return new_driver529 @validate_arguments530 def wait_for_ready_state_complete(self, timeout: OptionalInt = None):531 """Waits for the "readyState" of the page to be "complete".532 Returns True when the method completes.533 """534 self.__check_scope__()535 self.__check_browser__()536 timeout = self.get_timeout(timeout, constants.EXTREME_TIMEOUT)537 wait_for_ready_state_complete(self.driver, timeout)538 self.wait_for_angularjs(timeout=constants.MINI_TIMEOUT)539 if self.config.getoption("js_checking_on"):540 self.assert_no_js_errors()541 self.__ad_block_as_needed()542 return True543 def wait_for_angularjs(self, timeout: OptionalInt = None, **kwargs):544 """Waits for Angular components of the page to finish loading.545 Returns True when the method completes.546 """547 self.__check_scope__()548 timeout = self.get_timeout(timeout, constants.MINI_TIMEOUT)549 wait_for_angularjs(self.driver, timeout, **kwargs)550 return True551 def bring_active_window_to_front(self):552 """Brings the active browser window to the front.553 This is useful when multiple drivers are being used."""554 self.__check_scope__()555 try:556 if not self.__is_in_frame():557 # Only bring the window to the front if not in a frame558 # because the driver resets itself to default content.559 logger.debug("Bring the window to the front, since is not in a frame")560 self.switch_to_window(self.driver.current_window_handle)561 except WebDriverException:562 pass563 def _generate_driver_logs(self, driver: WebDriver):564 from ..contrib.rich.consoles import get_html_console565 from ..contrib.rich.themes import DRACULA_TERMINAL_THEME566 from ..contrib.rich.html_formats import CONSOLE_HTML_FORMAT567 console = get_html_console()568 from time import localtime, strftime569 dc = dictor570 log_path: pathlib.Path = dict(settings.PROJECT_PATHS).get("LOGS")571 s_id = driver.session_id572 from rich.table import Table573 for log_type in driver.log_types:574 file_name_path = log_path.joinpath(f'{log_type}_{s_id}.html')575 table = Table(title="test table", caption="table caption", expand=False)576 logs = self.driver.get_log(log_type)577 for entry in logs:578 local = localtime(dc(entry, "timestamp"))579 table.add_row(580 strftime(local, "X x"),581 dc(entry, "level"),582 dc(entry, "message"),583 dc(entry, "source")584 )585 console.save_html(586 str(file_name_path),587 theme=DRACULA_TERMINAL_THEME,588 code_format=CONSOLE_HTML_FORMAT,589 clear=True590 )591 # endregion WebDriver Actions592 # region WebElement Actions593 def __scroll_to_element(self, element: WebElement, how: SeleniumBy, selector: str) -> None:594 success = scroll_to_element(self.driver, element)595 if not success and selector:596 self.wait_for_ready_state_complete()597 element = wait_for_element_visible(self.driver, how, selector, timeout=constants.SMALL_TIMEOUT)598 demo_mode_pause_if_active(tiny=True)599 def is_link_text_present(self, link_text: str):600 """601 Returns True if the link text appears in the HTML of the page.602 The element doesn't need to be visible,603 such as elements hidden inside a dropdown selection604 :param link_text: the text to search605 :return: rue if the link text appears in the HTML of the page606 """607 logger.debug("Determine if link text: \"{text}\" can be found on DOM", text=link_text)608 self.wait_for_ready_state_complete()609 soup = self.get_beautiful_soup(self.get_page_source())610 html_links = soup.find_all("a")611 for html_link in html_links:612 if html_link.text.strip() == link_text.strip():613 logger.debug("link text: {text} was located", text=link_text)614 return True615 logger.debug("link text: {text} was not located", text=link_text)616 return False617 def click_link_text(self, link_text: str, timeout: OptionalInt = None):618 self.__check_scope__()619 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)620 if self.driver.capabilities.get("browserName") == "safari":621 ...622 if not self.is_link_text_present(link_text):623 wait_for_link_text_present(self.driver, link_text, timeout=timeout)624 pre_action_url = self.get_current_url()625 try:626 element = self.wait_for_link_text_visible(link_text, timeout=0.2)627 self.__demo_mode_highlight_if_active(link_text, by=By.LINK_TEXT)628 try:629 element.click()630 except (StaleElementReferenceException, ElementNotInteractableException):631 self.wait_for_ready_state_complete()632 time.sleep(0.16)633 element = self.wait_for_link_text_visible(634 link_text, timeout=timeout635 )636 element.click()637 except Exception:638 found_css = False639 text_id = self.get_link_attribute(link_text, "id", False)640 if text_id:641 link_css = '[id="%s"]' % link_text642 found_css = True643 if not found_css:644 href = self.__get_href_from_link_text(link_text, False)645 if href:646 if href.startswith("/") or page_utils.is_valid_url(href):647 link_css = '[href="%s"]' % href648 found_css = True649 if not found_css:650 ngclick = self.get_link_attribute(link_text, "ng-click", False)651 if ngclick:652 link_css = '[ng-click="%s"]' % ngclick653 found_css = True654 if not found_css:655 onclick = self.get_link_attribute(link_text, "onclick", False)656 if onclick:657 link_css = '[onclick="%s"]' % onclick658 found_css = True659 success = False660 if found_css:661 if self.is_element_visible(link_css):662 self.click(link_css)663 success = True664 else:665 # The link text might be hidden under a dropdown menu666 success = self.__click_dropdown_link_text(667 link_text, link_css668 )669 if not success:670 element = self.wait_for_link_text_visible(671 link_text, timeout=settings.MINI_TIMEOUT672 )673 element.click()674 if settings.WAIT_FOR_RSC_ON_CLICKS:675 self.wait_for_ready_state_complete()676 if self.config.getoption("demo_mode"):677 if self.driver.current_url != pre_action_url:678 demo_mode_pause_if_active()679 else:680 demo_mode_pause_if_active(tiny=True)681 elif self.config.getoption("slow_mode"):682 self._slow_mode_pause_if_active()683 def click_partial_link_text(self, partial_link_text: str, timeout: OptionalInt = None):684 ...685 def is_link_text_visible(self, link_text):686 self.wait_for_ready_state_complete()687 time.sleep(0.01)688 return is_element_visible(self.driver, By.LINK_TEXT, link_text)689 def is_partial_link_text_visible(self, partial_link_text):690 self.wait_for_ready_state_complete()691 time.sleep(0.01)692 return is_element_visible(self.driver, By.PARTIAL_LINK_TEXT, partial_link_text)693 @validate_arguments694 def click(695 self,696 how: SeleniumBy,697 selector: str = Field(default="", strict=True, min_length=1),698 timeout: OptionalInt = None,699 delay: float = 0.0,700 scroll=True701 ) -> None:702 self.__check_scope__()703 logger.debug("Performing a click on {}:'{}'", how.upper(), selector)704 self.get_timeout(timeout, constants.SMALL_TIMEOUT)705 if delay and (type(delay) in [int, float]) and delay > 0:706 time.sleep(delay)707 if how == By.LINK_TEXT:708 if not self.is_link_text_visible(selector):709 # Handle a special case of links hidden in dropdowns710 self.click_link_text(selector, timeout=timeout)711 return712 if how == By.PARTIAL_LINK_TEXT:713 if not self.is_partial_link_text_visible(selector):714 # Handle a special case of partial links hidden in dropdowns715 self.click_partial_link_text(selector, timeout=timeout)716 return717 if is_shadow_selector(selector):718 shadow_click(self.driver, selector)719 return720 element = wait_for_element_interactable(self.driver, how, selector, timeout=timeout)721 demo_mode_highlight_if_active(self.driver, how, selector)722 demo_mode = self.config.getoption("demo_mode", False)723 slow_mode = self.config.getoption("slow_mode", False)724 if scroll and not demo_mode and not slow_mode:725 self.__scroll_to_element(element, how, selector)726 pre_action_url = self.driver.current_url727 def handle_anchor():728 # Handle a special case of opening a new tab (headless)729 try:730 href = element.get_attribute("href").strip()731 onclick = element.get_attribute("onclick")732 target = element.get_attribute("target")733 new_tab = False734 if target == "_blank":735 _new_tab = True736 if new_tab and self.__looks_like_a_page_url(href):737 if onclick:738 try:739 self.execute_script(onclick)740 except WebDriverException | JavascriptException:741 pass742 current_window = self.driver.current_window_handle743 self.open_new_window()744 try:745 self.open(href)746 except WebDriverException:747 pass748 self.switch_to_window(current_window)749 return750 except WebDriverException:751 pass752 def handle_safari():753 if how == By.LINK_TEXT:754 self.__jquery_click(how, selector)755 else:756 self.__js_click(how, selector)757 def retry_on_stale():758 nonlocal element759 element = wait_for_element_interactable(self.driver, how, selector, timeout=timeout)760 try:761 self.__scroll_to_element(element, how, selector)762 except WebDriverException:763 pass764 if self.driver.capabilities.get("browserName") == "safari":765 handle_safari()766 else:767 element.click()768 def retry_on_element_not_interactable():769 nonlocal element770 element = wait_for_element_interactable(self.driver, how, selector, timeout=timeout)771 if element.tag_name == "a":772 handle_anchor()773 self.__scroll_to_element(element, how, selector)774 if self.driver.capabilities.get("browserName") == "safari":775 handle_safari()776 else:777 element.click()778 def retry_move_target_or_wd():779 try:780 js_click(how, selector)781 except WebDriverException | JavascriptException:782 try:783 jquery_click(how, selector)784 except WebDriverException | JavascriptException:785 nonlocal element786 element = wait_for_element_interactable(self.driver, how, selector, timeout=timeout)787 element.click()788 try:789 if self.driver.capabilities.get("browserName") == "safari":790 handle_safari()791 else:792 try:793 if self.config.getoption("headless") and element.tag_name == "a":794 # Handle a special case of opening a new tab (headless)795 handle_anchor()796 except WebDriverException:797 pass798 # Normal click799 logger.debug("Executing normal webelement click")800 element.click()801 except StaleElementReferenceException:802 logger.debug("Recovering from StaleElementReferenceException")803 self.wait_for_ready_state_complete()804 time.sleep(0.16)805 retry_on_stale()806 except ElementNotInteractableException:807 logger.debug("Recovering from ElementNotInteractableException")808 self.wait_for_ready_state_complete()809 time.sleep(0.1)810 retry_on_element_not_interactable()811 except WebDriverException | MoveTargetOutOfBoundsException as e:812 logger.debug("Recovering from {e_type}", e_type=e.__class__.__name__)813 self.wait_for_ready_state_complete()814 retry_move_target_or_wd()815 if settings.WAIT_FOR_RSC_ON_CLICKS:816 self.wait_for_ready_state_complete()817 if demo_mode:818 if self.driver.current_url != pre_action_url:819 demo_mode_pause_if_active()820 else:821 demo_mode_pause_if_active(tiny=True)822 elif slow_mode:823 self._slow_mode_pause_if_active()824 def slow_click(825 self,826 how: SeleniumBy,827 selector: str = Field(default="", strict=True, min_length=1),828 timeout: OptionalInt = None,829 ) -> None:830 """831 Similar to click(), but pauses for a brief moment before clicking.832 When used in combination with setting the user-agent, it can often833 bypass bot-detection by tricking websites into thinking that you're834 not a bot. (Useful on websites that block web automation tools.)835 Here's an example message from GitHub's bot-blocker:836 ``You have triggered an abuse detection mechanism...``837 :param how: the type of selector being used838 :param selector: the locator for identifying the page element (required)839 :param timeout: the time to wait for the element in seconds840 """841 self.__check_scope__()842 logger.debug("Performing a slow click on {}:'{}'", how.upper(), selector)843 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)844 demo_mode = self.config.getoption("demo_mode", False)845 slow_mode = self.config.getoption("slow_mode", False)846 if not demo_mode and not slow_mode:847 self.click(how, selector, timeout=timeout, delay=1.05)848 elif slow_mode:849 self.click(how, selector, timeout=timeout, delay=0.65)850 else:851 self.click(how, selector, timeout=timeout, delay=0.25)852 def double_click(853 self,854 how: SeleniumBy,855 selector: str = Field(default="", strict=True, min_length=1),856 timeout: OptionalInt = None,857 ) -> None:858 self.__check_scope__()859 logger.debug("Performing a double-click on {}:'{}'", how.upper(), selector)860 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)861 element = wait_for_element_interactable(self.driver, how, selector, timeout)862 @validate_arguments863 def slow_scroll_to(864 self,865 how: SeleniumBy,866 selector: str = Field(default="", strict=True, min_length=1),867 timeout: OptionalInt = None868 ):869 """ Slow motion scroll to destination """870 self.__check_scope__()871 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)872 element = self.wait_for_element_visible(how, selector, timeout)873 try:874 scroll_distance = get_scroll_distance_to_element(875 self.driver, element876 )877 if abs(scroll_distance) > settings.SSMD:878 jquery_slow_scroll_to(how, selector)879 else:880 slow_scroll_to_element(element)881 except WebDriverException:882 self.wait_for_ready_state_complete()883 time.sleep(0.12)884 element = self.wait_for_element_visible(how, selector, timeout)885 slow_scroll_to_element(element)886 @validate_arguments887 def wait_for_element_visible(888 self,889 how: SeleniumBy,890 selector: str = Field(default="", strict=True, min_length=1),891 timeout: OptionalInt = None892 ):893 self.__check_scope__()894 timeout = self.get_timeout(timeout, constants.LARGE_TIMEOUT)895 if is_shadow_selector(selector):896 return wait_for_shadow_element_visible(self.driver, selector, timeout)897 return wait_for_element_visible(self.driver, how, selector, timeout)898 def wait_for_link_text_visible(self, link_text, timeout=None) -> WebElement:899 self.__check_scope__()900 timeout = self.get_timeout(timeout, constants.LARGE_TIMEOUT)901 return self.wait_for_element_visible(By.LINK_TEXT, link_text, timeout=timeout)902 def wait_for_element_present(903 self,904 how: SeleniumBy,905 selector: str = Field(default="", strict=True, min_length=1),906 timeout: OptionalInt = None907 ):908 """Waits for an element to appear in the HTML of a page.909 The element does not need be visible (it may be hidden)."""910 self.__check_scope__()911 timeout = self.get_timeout(timeout, constants.LARGE_TIMEOUT)912 if is_shadow_selector(selector):913 return wait_for_shadow_element_present(self.driver, selector, timeout)914 return wait_for_element_present(self.driver, how, selector, timeout)915 def get_link_attribute(self, link_text: str, attribute: str, hard_fail=True):916 """917 Finds a link by link text and then returns the attribute's value.918 If the link text or attribute cannot be found, an exception will919 get raised if hard_fail is True (otherwise None is returned).920 :param link_text: The link test to find921 :param attribute: the attribute name922 :param hard_fail:923 :return:924 """925 self.wait_for_ready_state_complete()926 soup = self.get_beautiful_soup(self.get_page_source())927 logger.trace("Searching for anchor using BeautifulSoup")928 html_links = soup.find_all("a")929 logger.trace("Found {count} anchors on current html source page", count=len(html_links))930 for html_link in html_links:931 if html_link.text.strip() == link_text.strip():932 if html_link.has_attr(attribute):933 attribute_value = html_link.get(attribute)934 return attribute_value935 if hard_fail:936 raise WebDriverException(f"Unable to find attribute {attribute} from link text {link_text}!")937 else:938 return None939 if hard_fail:940 raise WebDriverException("Link text {link_text} was not found!")941 else:942 return None943 @validate_arguments944 def is_element_visible(self, how: SeleniumBy, selector: str = Field(default="", strict=True, min_length=1)):945 self.wait_for_ready_state_complete()946 return is_element_visible(self.driver, how, selector)947 @validate_arguments948 def is_element_enabled(self, how: SeleniumBy, selector: str = Field(default="", strict=True, min_length=1)):949 self.wait_for_ready_state_complete()950 return is_element_enabled(self.driver, how, selector)951 # region highlight952 def highlight(953 self,954 how: SeleniumBy,955 selector: str = Field(..., strict=True, min_length=1),956 scroll=True957 ) -> None:958 self.__check_scope__()959 loops = settings.HIGHLIGHT_LOOPS960 element = wait_for_element_visible(self.driver, how, selector, constants.SMALL_TIMEOUT)961 if scroll:962 try:963 if self.driver.capabilities.get("browserName") == "safari":964 ...965 else:966 jquery_slow_scroll_to(self.driver, how, selector)967 except WebDriverException | JavascriptException as e:968 logger.warning('Exception while scrolling to element {how}:"{selector}"', str(e))969 self.wait_for_ready_state_complete()970 time.sleep(0.12)971 element = wait_for_element_visible(self.driver, how, selector, constants.SMALL_TIMEOUT)972 slow_scroll_to_element(element)973 selector = self.convert_to_css_selector(how, selector)974 if self.config.getoption("highlights", False):975 loops = self.config.getoption("highlights")976 loops = int(loops)977 style = element.get_attribute("style")978 if style:979 if "box-shadow: " in style:980 box_start = style.find("box-shadow: ")981 box_end = style.find(";", box_start) + 1982 original_box_shadow = style[box_start:box_end]983 o_bs = original_box_shadow984 selector = make_css_match_first_element_only(selector)985 selector = re.escape(selector)986 selector = escape_quotes_if_needed(selector)...

Full Screen

Full Screen

js_actions.py

Source:js_actions.py Github

copy

Full Screen

...167 :param selector:168 :return:169 """170 pass171 def _slow_scroll_to_element(self, element: WebElement) -> bool:172 ...173 def slow_scroll_to_element(self, element: WebElement) -> bool:174 """175 :param element:176 :return:177 """178 pass179 def scroll_to_element(self, element: WebElement) -> bool:180 """181 :param element:182 :return:183 """184 pass185 def highlight_with_js(186 self,187 selector: str = Field(..., strict=True, min_length=1),...

Full Screen

Full Screen

demo_mode.py

Source:demo_mode.py Github

copy

Full Screen

...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