How to use __ad_block_as_needed method in SeleniumBase

Best Python code snippet using SeleniumBase

webdriver_test.py

Source:webdriver_test.py Github

copy

Full Screen

...258 else:259 # A smaller subset of self.wait_for_ready_state_complete()260 self.wait_for_angularjs(timeout=settings.MINI_TIMEOUT)261 if self.driver.current_url != pre_action_url:262 self.__ad_block_as_needed()263 if browser_name == "safari":264 time.sleep(0.02)265 if self.demo_mode:266 if self.driver.current_url != pre_action_url:267 self._demo_mode_pause_if_active()268 else:269 self._demo_mode_pause_if_active(tiny=True)270 elif self.slow_mode:271 self._slow_mode_pause_if_active()272 @validate_arguments273 def slow_click(274 self,275 how: SeleniumBy,276 selector: str = Field(default="", strict=True, min_length=1),277 timeout: OptionalInt = None278 ) -> None:279 self.__check_scope__()280 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)281 if not self.demo_mode and not self.slow_mode:282 self.click(how, selector, timeout=timeout, delay=1.05)283 elif self.slow_mode:284 self.click(how, selector, timeout=timeout, delay=0.65)285 else:286 self.click(how, selector, timeout=timeout, delay=0.25)287 def double_click(288 self,289 how: SeleniumBy,290 selector: str = Field(..., strict=True, min_length=1),291 timeout: OptionalInt = None,292 ) -> None:293 from selenium.webdriver.common.action_chains import ActionChains294 self.__check_scope__()295 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)296 element = element_actions.wait_for_element_interactable(self.driver, how, selector, timeout=timeout)297 self.__demo_mode_highlight_if_active(how, selector)298 if not self.demo_mode and not self.slow_mode:299 self.__scroll_to_element(element, how, selector)300 self.wait_for_ready_state_complete()301 logger.debug("Find the element one more time in case scrolling hid it")302 element = element_actions.wait_for_element_visible(self.driver, how, selector, timeout=timeout)303 pre_action_url = self.driver.current_url304 try:305 if self.browser == "safari":306 # Jump to the "except" block where the other script should work307 raise WebDriverException("This Exception will be caught.")308 actions = ActionChains(self.driver)309 actions.double_click(element).perform()310 except WebDriverException:311 css_selector = self.convert_to_css_selector(how, selector)312 css_selector = re.escape(css_selector) # Add "\\" to special chars313 css_selector = shared.escape_quotes_if_needed(css_selector)314 double_click_script = (315 """var targetElement1 = document.querySelector('%s');316 var clickEvent1 = document.createEvent('MouseEvents');317 clickEvent1.initEvent('dblclick', true, true);318 targetElement1.dispatchEvent(clickEvent1);"""319 % css_selector320 )321 if ":contains\\(" not in css_selector:322 self.execute_script(double_click_script)323 else:324 double_click_script = (325 """jQuery('%s').dblclick();""" % css_selector326 )327 self.safe_execute_script(double_click_script)328 if settings.WAIT_FOR_RSC_ON_CLICKS:329 self.wait_for_ready_state_complete()330 else:331 # A smaller subset of self.wait_for_ready_state_complete()332 self.wait_for_angularjs(timeout=settings.MINI_TIMEOUT)333 if self.driver.current_url != pre_action_url:334 self._ad_block_as_needed()335 if self.demo_mode:336 if self.driver.current_url != pre_action_url:337 self._demo_mode_pause_if_active()338 else:339 self._demo_mode_pause_if_active(tiny=True)340 elif self.slow_mode:341 self._slow_mode_pause_if_active()342 def click_chain(343 self, selectors_list, by=By.CSS_SELECTOR, timeout=None, spacing=0344 ):345 """This method clicks on a list of elements in succession.346 @Params347 selectors_list - The list of selectors to click on.348 by - The type of selector to search by (Default: CSS_Selector).349 timeout - How long to wait for the selector to be visible.350 spacing - The amount of time to wait between clicks (in seconds).351 """352 self.__check_scope__()353 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)354 for selector in selectors_list:355 self.click(selector, by=by, timeout=timeout)356 if spacing > 0:357 time.sleep(spacing)358 def update_text(359 self,360 text: str | None,361 how: SeleniumBy,362 selector: str = Field(..., strict=True, min_length=1),363 timeout: OptionalInt = None,364 retry=False365 ) -> None:366 self.__check_scope__()367 timeout = self.get_timeout(timeout, constants.LARGE_TIMEOUT)368 if self._is_shadow_selector(selector):369 self._shadow.shadow_type(selector, text, timeout)370 return371 element = self.wait_for_element_interactable(how, selector, timeout)372 self.__demo_mode_highlight_if_active(how, selector)373 if not self.demo_mode and not self.slow_mode:374 self.__scroll_to_element(element, how, selector)375 try:376 element.clear() # May need https://stackoverflow.com/a/50691625377 backspaces = Keys.BACK_SPACE * 42 # Is the answer to everything378 element.send_keys(backspaces) # In case autocomplete keeps text379 except (StaleElementReferenceException, ElementNotInteractableException):380 self.wait_for_ready_state_complete()381 time.sleep(0.16)382 element = self.wait_for_element_visible(how, selector, timeout)383 try:384 element.clear()385 except Exception:386 pass # Clearing the text field first might not be necessary387 except Exception:388 pass # Clearing the text field first might not be necessary389 self._demo_mode_pause_if_active(tiny=True)390 pre_action_url = self.driver.current_url391 if type(text) is int or type(text) is float:392 text = str(text)393 try:394 if not text.endswith("\n"):395 element.send_keys(text)396 if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:397 self.wait_for_ready_state_complete()398 else:399 element.send_keys(text[:-1])400 element.send_keys(Keys.RETURN)401 if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:402 self.wait_for_ready_state_complete()403 except (StaleElementReferenceException, ElementNotInteractableException):404 self.wait_for_ready_state_complete()405 time.sleep(0.16)406 element = self.wait_for_element_visible(how, selector, timeout=timeout)407 element.clear()408 if not text.endswith("\n"):409 element.send_keys(text)410 else:411 element.send_keys(text[:-1])412 element.send_keys(Keys.RETURN)413 if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:414 self.wait_for_ready_state_complete()415 if (416 retry417 and element.get_attribute("value") != text418 and not text.endswith("\n")419 ):420 logger.debug("update_text() is falling back to JavaScript!")421 self.set_value(selector, text, by=by)422 if self.demo_mode:423 if self.driver.current_url != pre_action_url:424 self._demo_mode_pause_if_active()425 else:426 self._demo_mode_pause_if_active(tiny=True)427 elif self.slow_mode:428 self._slow_mode_pause_if_active()429 @validate_arguments430 def add_text(431 self,432 text: str | None,433 how: SeleniumBy,434 selector: str = Field(..., strict=True, min_length=1),435 timeout: OptionalInt = None436 ):437 """The more-reliable version of driver.send_keys()438 Similar to update_text(), but won't clear the text field first."""439 self.__check_scope__()440 timeout = self.get_timeout(timeout, constants.LARGE_TIMEOUT)441 if self._is_shadow_selector(selector):442 self._shadow.shadow_type(selector, text, timeout, clear_first=False)443 return444 element = self.wait_for_element_visible(how, selector, timeout)445 self.__demo_mode_highlight_if_active(how, selector)446 if not self.demo_mode and not self.slow_mode:447 self.__scroll_to_element(element, how, selector)448 pre_action_url = self.driver.current_url449 if type(text) is int or type(text) is float:450 text = str(text)451 try:452 if not text.endswith("\n"):453 element.send_keys(text)454 else:455 element.send_keys(text[:-1])456 element.send_keys(Keys.RETURN)457 if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:458 self.wait_for_ready_state_complete()459 except (StaleElementReferenceException, ElementNotInteractableException):460 self.wait_for_ready_state_complete()461 time.sleep(0.16)462 element = self.wait_for_element_visible(how, selector, timeout)463 if not text.endswith("\n"):464 element.send_keys(text)465 else:466 element.send_keys(text[:-1])467 element.send_keys(Keys.RETURN)468 if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:469 self.wait_for_ready_state_complete()470 if self.demo_mode:471 if self.driver.current_url != pre_action_url:472 self._demo_mode_pause_if_active()473 else:474 self._demo_mode_pause_if_active(tiny=True)475 elif self.slow_mode:476 self._slow_mode_pause_if_active()477 def submit(self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1)):478 """ Alternative to self.driver.find_element_by_*(SELECTOR).submit() """479 self.__check_scope__()480 element = self.wait_for_element_visible(how, selector, timeout=constants.SMALL_TIMEOUT)481 element.submit()482 self._demo_mode_pause_if_active()483 def clear(484 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1), timeout: OptionalInt = None485 ):486 self.__check_scope__()487 timeout = self.get_timeout(timeout, constants.LARGE_TIMEOUT)488 if self._is_shadow_selector(selector):489 self._shadow.shadow_clear(selector, timeout)490 return491 element = self.wait_for_element_visible(how, selector, timeout)492 self.scroll_to(how, selector, timeout=timeout)493 try:494 element.clear()495 backspaces = Keys.BACK_SPACE * 42 # Autofill Defense496 element.send_keys(backspaces)497 except (StaleElementReferenceException, ElementNotInteractableException):498 self.wait_for_ready_state_complete()499 time.sleep(0.16)500 element = self.wait_for_element_visible(how, selector, timeout)501 element.clear()502 try:503 backspaces = Keys.BACK_SPACE * 42 # Autofill Defense504 element.send_keys(backspaces)505 except Exception:506 pass507 except Exception:508 element.clear()509 def focus(510 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1), timeout: OptionalInt = None511 ):512 self.__check_scope__()513 timeout = self.get_timeout(timeout, constants.LARGE_TIMEOUT)514 element = self.wait_for_element_visible(how, selector, timeout)515 self.scroll_to(how, selector, timeout=timeout)516 try:517 element.send_keys(Keys.NULL)518 except (StaleElementReferenceException, ElementNotInteractableException):519 self.wait_for_ready_state_complete()520 time.sleep(0.12)521 element = self.wait_for_element_visible(how, selector, timeout)522 try:523 element.send_keys(Keys.NULL)524 except ElementNotInteractableException:525 # Non-interactable element. Skip focus and continue.526 pass527 self._demo_mode_pause_if_active()528 def refresh_page(self):529 self.__check_scope__()530 self.__last_page_load_url = None531 self._clear_out_console_logs()532 self.driver.refresh()533 self.wait_for_ready_state_complete()534 def refresh(self):535 """ The shorter version of self.refresh_page() """536 self.refresh_page()537 def get_origin(self):538 self.__check_scope__()539 return self.execute_script("return window.location.origin;")540 def get_page_source(self):541 self.wait_for_ready_state_complete()542 return self.driver.page_source543 def get_page_title(self):544 self.wait_for_ready_state_complete()545 self.wait_for_element_present("title", timeout=settings.SMALL_TIMEOUT)546 time.sleep(0.03)547 return self.driver.title548 def get_title(self):549 """ The shorter version of self.get_page_title() """550 return self.get_page_title()551 def get_user_agent(self) -> str:552 self.__check_scope__()553 self.__check_browser__()554 user_agent = self.driver.execute_script("return navigator.userAgent;")555 return user_agent556 def get_locale_code(self) -> str:557 self.__check_scope__()558 self.__check_browser__()559 locale_code = self.driver.execute_script(560 "return navigator.language || navigator.languages[0];"561 )562 return locale_code563 def go_back(self):564 self.__check_scope__()565 self.__last_page_load_url = None566 self.driver.back()567 if self.browser == "safari":568 self.wait_for_ready_state_complete()569 self.driver.refresh()570 self.wait_for_ready_state_complete()571 self._demo_mode_pause_if_active()572 def go_forward(self):573 self.__check_scope__()574 self.__last_page_load_url = None575 self.driver.forward()576 self.wait_for_ready_state_complete()577 self._demo_mode_pause_if_active()578 def open_start_page(self):579 self.__check_scope__()580 start_page = self.start_page581 if type(start_page) is str:582 start_page = start_page.strip() # Remove extra whitespace583 if start_page and len(start_page) >= 4:584 if page_utils.is_valid_url(start_page):585 self.open(start_page)586 else:587 new_start_page = "https://" + start_page588 if page_utils.is_valid_url(new_start_page):589 self.__dont_record_open = True590 self.open(new_start_page)591 self.__dont_record_open = False592 else:593 logger.info('Invalid URL: "%s"!' % start_page)594 self.open("data:,")595 else:596 self.open("data:,")597 def open_if_not_url(self, url):598 """ Opens the url in the browser if it's not the current url. """599 self.__check_scope__()600 if self.driver.current_url != url:601 self.open(url)602 def is_element_present(self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1)):603 self.wait_for_ready_state_complete()604 if self._is_shadow_selector(selector):605 return self._shadow.is_shadow_element_present(selector)606 return element_actions.is_element_present(self.driver, how, selector)607 def is_element_visible(self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1)):608 self.wait_for_ready_state_complete()609 if self._is_shadow_selector(selector):610 return self._shadow.is_shadow_element_visible(selector)611 return element_actions.is_element_visible(self.driver, selector, by)612 def is_element_enabled(self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1)):613 self.wait_for_ready_state_complete()614 if self._is_shadow_selector(selector):615 return self._shadow.is_shadow_element_enabled(selector)616 return element_actions.is_element_enabled(self.driver, selector, by)617 def is_text_visible(618 self, text: str | None, how: SeleniumBy, selector: str = Field(default="html", strict=True, min_length=1)619 ):620 self.wait_for_ready_state_complete()621 time.sleep(0.01)622 if self._is_shadow_selector(selector):623 return self._shadow.is_shadow_text_visible(text, selector)624 return element_actions.is_text_visible(self.driver, text, selector, by)625 @validate_arguments626 def is_attribute_present(627 self,628 attribute_name: str,629 attribute_value: str | None,630 how: SeleniumBy,631 selector: str = Field(..., strict=True, min_length=1)632 ) -> bool:633 """Returns True if the element attribute/value is found.634 If the value is not specified, the attribute only needs to exist."""635 self.wait_for_ready_state_complete()636 time.sleep(0.01)637 if self._is_shadow_selector(selector):638 return self._shadow.is_shadow_attribute_present(selector, attribute_name, attribute_value)639 return element_actions.is_attribute_present(self.driver, attribute_name, attribute_value, how, selector)640 @validate_arguments641 def is_link_text_visible(self, link_text: str) -> bool:642 self.wait_for_ready_state_complete()643 time.sleep(0.01)644 return element_actions.is_element_visible(self.driver, link_text, by=By.LINK_TEXT)645 @validate_arguments646 def is_partial_link_text_visible(self, partial_link_text: str) -> bool:647 self.wait_for_ready_state_complete()648 time.sleep(0.01)649 return element_actions.is_element_visible(650 self.driver, partial_link_text, by=By.PARTIAL_LINK_TEXT651 )652 @validate_arguments653 def is_link_text_present(self, link_text: str) -> bool:654 """Returns True if the link text appears in the HTML of the page.655 The element doesn't need to be visible,656 such as elements hidden inside a dropdown selection."""657 self.wait_for_ready_state_complete()658 soup = self.get_beautiful_soup()659 html_links = soup.find_all("a")660 for html_link in html_links:661 if html_link.text.strip() == link_text.strip():662 return True663 return False664 @validate_arguments665 def is_partial_link_text_present(self, link_text: str) -> bool:666 """Returns True if the partial link appears in the HTML of the page.667 The element doesn't need to be visible,668 such as elements hidden inside a dropdown selection."""669 self.wait_for_ready_state_complete()670 soup = self.get_beautiful_soup()671 html_links = soup.find_all("a")672 for html_link in html_links:673 if link_text.strip() in html_link.text.strip():674 return True675 return False676 def get_link_attribute(self, link_text: str, attribute: str, hard_fail=True):677 self.wait_for_ready_state_complete()678 soup = self.get_beautiful_soup()679 html_links = soup.find_all("a")680 for html_link in html_links:681 if html_link.text.strip() == link_text.strip():682 if html_link.has_attr(attribute):683 attribute_value = html_link.get(attribute)684 return attribute_value685 if hard_fail:686 raise WebDriverException(f"Unable to find attribute {attribute} from link text {link_text}!")687 else:688 return None689 if hard_fail:690 raise Exception("Link text {%s} was not found!" % link_text)691 else:692 return None693 def get_link_text_attribute(self, link_text, attribute, hard_fail=True):694 return self.get_link_attribute(link_text, attribute, hard_fail)695 def get_partial_link_text_attribute(696 self, link_text, attribute, hard_fail=True697 ):698 self.wait_for_ready_state_complete()699 soup = self.get_beautiful_soup()700 html_links = soup.find_all("a")701 for html_link in html_links:702 if link_text.strip() in html_link.text.strip():703 if html_link.has_attr(attribute):704 attribute_value = html_link.get(attribute)705 return attribute_value706 if hard_fail:707 raise Exception(708 "Unable to find attribute {%s} from "709 "partial link text {%s}!" % (attribute, link_text)710 )711 else:712 return None713 if hard_fail:714 raise Exception(715 "Partial Link text {%s} was not found!" % link_text716 )717 else:718 return None719 def click_link_text(self, link_text: str, timeout: OptionalInt = None):720 """ This method clicks link text on a page """721 # If using phantomjs, might need to extract and open the link directly722 self.__check_scope__()723 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)724 pre_action_url = self.driver.current_url725 pre_window_count = len(self.driver.window_handles)726 if self.browser == "phantomjs":727 if self.is_link_text_visible(link_text):728 element = self.wait_for_link_text_visible(729 link_text, timeout=timeout730 )731 element.click()732 return733 self.open(self.__get_href_from_link_text(link_text))734 return735 if self.browser == "safari":736 if self.demo_mode:737 self.wait_for_link_text_present(link_text, timeout=timeout)738 try:739 self.__jquery_slow_scroll_to(link_text, by=By.LINK_TEXT)740 except Exception:741 element = self.wait_for_link_text_visible(742 link_text, timeout=timeout743 )744 self.__slow_scroll_to_element(element)745 o_bs = "" # original_box_shadow746 loops = settings.HIGHLIGHTS747 selector = self.convert_to_css_selector(748 link_text, by=By.LINK_TEXT749 )750 selector = self.__make_css_match_first_element_only(selector)751 try:752 selector = re.escape(selector)753 selector = shared.escape_quotes_if_needed(selector)754 self.__highlight_with_jquery(selector, loops, o_bs)755 except Exception:756 pass # JQuery probably couldn't load. Skip highlighting.757 self.__jquery_click(link_text, by=By.LINK_TEXT)758 return759 if not self.is_link_text_present(link_text):760 self.wait_for_link_text_present(link_text, timeout=timeout)761 pre_action_url = self.get_current_url()762 try:763 element = self.wait_for_link_text_visible(link_text, timeout=0.2)764 self.__demo_mode_highlight_if_active(link_text, by=By.LINK_TEXT)765 try:766 element.click()767 except (StaleElementReferenceException, ElementNotInteractableException):768 self.wait_for_ready_state_complete()769 time.sleep(0.16)770 element = self.wait_for_link_text_visible(771 link_text, timeout=timeout772 )773 element.click()774 except Exception:775 found_css = False776 text_id = self.get_link_attribute(link_text, "id", False)777 if text_id:778 link_css = '[id="%s"]' % link_text779 found_css = True780 if not found_css:781 href = self.__get_href_from_link_text(link_text, False)782 if href:783 if href.startswith("/") or page_utils.is_valid_url(href):784 link_css = '[href="%s"]' % href785 found_css = True786 if not found_css:787 ngclick = self.get_link_attribute(link_text, "ng-click", False)788 if ngclick:789 link_css = '[ng-click="%s"]' % ngclick790 found_css = True791 if not found_css:792 onclick = self.get_link_attribute(link_text, "onclick", False)793 if onclick:794 link_css = '[onclick="%s"]' % onclick795 found_css = True796 success = False797 if found_css:798 if self.is_element_visible(link_css):799 self.click(link_css)800 success = True801 else:802 # The link text might be hidden under a dropdown menu803 success = self.__click_dropdown_link_text(804 link_text, link_css805 )806 if not success:807 element = self.wait_for_link_text_visible(808 link_text, timeout=settings.MINI_TIMEOUT809 )810 element.click()811 latest_window_count = len(self.driver.window_handles)812 if (813 latest_window_count > pre_window_count814 and (815 self.recorder_mode816 or (817 settings.SWITCH_TO_NEW_TABS_ON_CLICK818 and self.driver.current_url == pre_action_url819 )820 )821 ):822 self.__switch_to_newest_window_if_not_blank()823 if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:824 self.wait_for_ready_state_complete()825 if self.demo_mode:826 if self.driver.current_url != pre_action_url:827 self._demo_mode_pause_if_active()828 else:829 self._demo_mode_pause_if_active(tiny=True)830 elif self.slow_mode:831 self._slow_mode_pause_if_active()832 def click_partial_link_text(self, partial_link_text: str, timeout: OptionalInt = None):833 """ This method clicks the partial link text on a page. """834 # If using phantomjs, might need to extract and open the link directly835 self.__check_scope__()836 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)837 if self.browser == "phantomjs":838 if self.is_partial_link_text_visible(partial_link_text):839 element = self.wait_for_partial_link_text(partial_link_text)840 element.click()841 return842 soup = self.get_beautiful_soup()843 html_links = soup.fetch("a")844 for html_link in html_links:845 if partial_link_text in html_link.text:846 for html_attribute in html_link.attrs:847 if html_attribute[0] == "href":848 href = html_attribute[1]849 if href.startswith("//"):850 link = "http:" + href851 elif href.startswith("/"):852 url = self.driver.current_url853 domain_url = self.get_domain_url(url)854 link = domain_url + href855 else:856 link = href857 self.open(link)858 return859 raise Exception(860 "Could not parse link from partial link_text "861 "{%s}" % partial_link_text862 )863 raise Exception(864 "Partial link text {%s} was not found!" % partial_link_text865 )866 if not self.is_partial_link_text_present(partial_link_text):867 self.wait_for_partial_link_text_present(868 partial_link_text, timeout=timeout869 )870 pre_action_url = self.driver.current_url871 pre_window_count = len(self.driver.window_handles)872 try:873 element = self.wait_for_partial_link_text(874 partial_link_text, timeout=0.2875 )876 self.__demo_mode_highlight_if_active(877 partial_link_text, by=By.LINK_TEXT878 )879 try:880 element.click()881 except (StaleElementReferenceException, ElementNotInteractableException):882 self.wait_for_ready_state_complete()883 time.sleep(0.16)884 element = self.wait_for_partial_link_text(885 partial_link_text, timeout=timeout886 )887 element.click()888 except Exception:889 found_css = False890 text_id = self.get_partial_link_text_attribute(891 partial_link_text, "id", False892 )893 if text_id:894 link_css = '[id="%s"]' % partial_link_text895 found_css = True896 if not found_css:897 href = self.__get_href_from_partial_link_text(898 partial_link_text, False899 )900 if href:901 if href.startswith("/") or page_utils.is_valid_url(href):902 link_css = '[href="%s"]' % href903 found_css = True904 if not found_css:905 ngclick = self.get_partial_link_text_attribute(906 partial_link_text, "ng-click", False907 )908 if ngclick:909 link_css = '[ng-click="%s"]' % ngclick910 found_css = True911 if not found_css:912 onclick = self.get_partial_link_text_attribute(913 partial_link_text, "onclick", False914 )915 if onclick:916 link_css = '[onclick="%s"]' % onclick917 found_css = True918 success = False919 if found_css:920 if self.is_element_visible(link_css):921 self.click(link_css)922 success = True923 else:924 # The link text might be hidden under a dropdown menu925 success = self.__click_dropdown_partial_link_text(926 partial_link_text, link_css927 )928 if not success:929 element = self.wait_for_partial_link_text(930 partial_link_text, timeout=settings.MINI_TIMEOUT931 )932 element.click()933 latest_window_count = len(self.driver.window_handles)934 if (935 latest_window_count > pre_window_count936 and (937 self.recorder_mode938 or (939 settings.SWITCH_TO_NEW_TABS_ON_CLICK940 and self.driver.current_url == pre_action_url941 )942 )943 ):944 self.__switch_to_newest_window_if_not_blank()945 if settings.WAIT_FOR_RSC_ON_PAGE_LOADS:946 self.wait_for_ready_state_complete()947 if self.demo_mode:948 if self.driver.current_url != pre_action_url:949 self._demo_mode_pause_if_active()950 else:951 self._demo_mode_pause_if_active(tiny=True)952 elif self.slow_mode:953 self._slow_mode_pause_if_active()954 def get_text(self, selector, by=By.CSS_SELECTOR, timeout=None):955 self.__check_scope__()956 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)957 if self._is_shadow_selector(selector):958 return self._shadow.get_shadow_text(selector, timeout)959 self.wait_for_ready_state_complete()960 time.sleep(0.01)961 element = element_actions.wait_for_element_visible(self.driver, how, selector, timeout)962 try:963 element_text = element.text964 if self.browser == "safari":965 element_text = element.get_attribute("innerText")966 except (StaleElementReferenceException, ElementNotInteractableException):967 self.wait_for_ready_state_complete()968 time.sleep(0.14)969 element = page_actions.wait_for_element_visible(970 self.driver, selector, by, timeout971 )972 element_text = element.text973 if self.browser == "safari":974 element_text = element.get_attribute("innerText")975 return element_text976 def get_attribute(977 self,978 selector,979 attribute,980 by=By.CSS_SELECTOR,981 timeout=None,982 hard_fail=True,983 ):984 """ This method uses JavaScript to get the value of an attribute. """985 self.__check_scope__()986 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)987 self.wait_for_ready_state_complete()988 time.sleep(0.01)989 if self._is_shadow_selector(selector):990 return self._shadow._get_shadow_attribute(991 selector, attribute, timeout=timeout992 )993 element_actions.wait_for_element_present(self.driver, how, selector, timeout)994 try:995 attribute_value = element.get_attribute(attribute)996 except (StaleElementReferenceException, ElementNotInteractableException):997 self.wait_for_ready_state_complete()998 time.sleep(0.14)999 element = element_actions.wait_for_element_present(self.driver, how, selector, timeout)1000 attribute_value = element.get_attribute(attribute)1001 if attribute_value is not None:1002 return attribute_value1003 else:1004 if hard_fail:1005 raise Exception(1006 "Element {%s} has no attribute {%s}!"1007 % (selector, attribute)1008 )1009 else:1010 return None1011 def set_attribute(1012 self,1013 selector,1014 attribute,1015 value,1016 by=By.CSS_SELECTOR,1017 timeout=None,1018 scroll=False,1019 ):1020 """This method uses JavaScript to set/update an attribute.1021 Only the first matching selector from querySelector() is used."""1022 self.__check_scope__()1023 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)1024 if scroll and self.is_element_visible(how, selector):1025 try:1026 self.scroll_to(selector, by=by, timeout=timeout)1027 except Exception:1028 pass1029 attribute = re.escape(attribute)1030 attribute = shared.escape_quotes_if_needed(attribute)1031 value = re.escape(value)1032 value = shared.escape_quotes_if_needed(value)1033 css_selector = self.convert_to_css_selector(selector, by=by)1034 css_selector = re.escape(css_selector) # Add "\\" to special chars1035 css_selector = shared.escape_quotes_if_needed(css_selector)1036 script = (1037 """document.querySelector('%s').setAttribute('%s','%s');"""1038 % (css_selector, attribute, value)1039 )1040 self.execute_script(script)1041 def set_attributes(self, selector, attribute, value, by=By.CSS_SELECTOR):1042 """This method uses JavaScript to set/update a common attribute.1043 All matching selectors from querySelectorAll() are used.1044 Example => (Make all links on a website redirect to Google):1045 self.set_attributes("a", "href", "https://google.com")"""1046 self.__check_scope__()1047 attribute = re.escape(attribute)1048 attribute = shared.escape_quotes_if_needed(attribute)1049 value = re.escape(value)1050 value = shared.escape_quotes_if_needed(value)1051 css_selector = self.convert_to_css_selector(selector, by=by)1052 css_selector = re.escape(css_selector) # Add "\\" to special chars1053 css_selector = shared.escape_quotes_if_needed(css_selector)1054 script = """var $elements = document.querySelectorAll('%s');1055 var index = 0, length = $elements.length;1056 for(; index < length; index++){1057 $elements[index].setAttribute('%s','%s');}""" % (1058 css_selector,1059 attribute,1060 value,1061 )1062 try:1063 self.execute_script(script)1064 except Exception:1065 pass1066 def set_attribute_all(1067 self, selector, attribute, value, by=By.CSS_SELECTOR1068 ):1069 """Same as set_attributes(), but using querySelectorAll naming scheme.1070 This method uses JavaScript to set/update a common attribute.1071 All matching selectors from querySelectorAll() are used.1072 Example => (Make all links on a website redirect to Google):1073 self.set_attribute_all("a", "href", "https://google.com")"""1074 self.set_attributes(selector, attribute, value, by=by)1075 def remove_attribute(1076 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1077 timeout: OptionalInt = None,1078 attribute_name: str = Field(..., min_length=1)1079 ):1080 self.__check_scope__()1081 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)1082 if self.is_element_visible(how, selector):1083 try:1084 self.scroll_to(how, selector, timeout=timeout)1085 except WebDriverException:1086 pass1087 attribute = re.escape(attribute_name)1088 attribute = shared.escape_quotes_if_needed(attribute)1089 css_selector = self.convert_to_css_selector(selector, by=by)1090 css_selector = re.escape(css_selector) # Add "\\" to special chars1091 css_selector = shared.escape_quotes_if_needed(css_selector)1092 script = f"document.querySelector('{css_selector}').removeAttribute('{attribute_name}');"1093 self.execute_script(script)1094 def remove_attributes(1095 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1096 attribute_name: str = Field(..., min_length=1)1097 ) -> None:1098 """This method uses JavaScript to remove a common attribute.1099 All matching selectors from querySelectorAll() are used."""1100 self.__check_scope__()1101 attribute = re.escape(attribute_name)1102 attribute = shared.escape_quotes_if_needed(attribute)1103 css_selector = self.convert_to_css_selector(how, selector)1104 css_selector = re.escape(css_selector) # Add "\\" to special chars1105 css_selector = shared.escape_quotes_if_needed(css_selector)1106 script = """var $elements = document.querySelectorAll('%s');1107 var index = 0, length = $elements.length;1108 for(; index < length; index++){1109 $elements[index].removeAttribute('%s');}""" % (css_selector, attribute_name)1110 try:1111 self.execute_script(script)1112 except WebDriverException | JavascriptException as e:1113 logger.warning(1114 "Exception {} caught while removing attribute from element ->\n{}",1115 e.__class__.__qualname__, str(e)1116 )1117 pass1118 def has_attribute(1119 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1120 timeout: OptionalInt = None,1121 attribute_name: str = Field(..., min_length=1)1122 ) -> bool:1123 self.__check_scope__()1124 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)1125 element = element_actions.wait_for_element_present(self.driver, how, selector, timeout)1126 return element_actions.has_attribute(element, attribute_name)1127 def get_property(1128 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1129 property_name=Field(..., min_length=1),1130 timeout: OptionalInt = None1131 ) -> Optional[Any]:1132 """Returns the property value of an element.1133 This is not the same as self.get_property_value(), which returns1134 the value of an element's computed style using a different algorithm.1135 If no result is found, an empty string (instead of None) is returned.1136 Example:1137 html_text = self.get_property(SELECTOR, "textContent")1138 """1139 self.__check_scope__()1140 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)1141 self.wait_for_ready_state_complete()1142 time.sleep(0.01)1143 element = element_actions.wait_for_element_present(self.driver, how, selector, timeout)1144 return element.get_property(property).strip()1145 @validate_arguments1146 def get_text_content(1147 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1148 property_name = Field(..., min_length=1),1149 timeout: OptionalInt = None1150 ) -> str:1151 """Returns the text that appears in the HTML for an element.1152 This is different from "self.get_text(selector, by=By.CSS_SELECTOR)"1153 because that only returns the visible text on a page for an element,1154 rather than the HTML text that's being returned from this method."""1155 self.__check_scope__()1156 return self.get_property(how, selector, property_name, timeout)1157 def get_property_value(1158 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1159 timeout: OptionalInt = None1160 ) -> Any:1161 """Returns the property value of a page element's computed style.1162 Example:1163 opacity = self.get_property_value("html body a", "opacity")1164 self.assertTrue(float(opacity) > 0, "Element not visible!")"""1165 self.__check_scope__()1166 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)1167 self.wait_for_ready_state_complete()1168 element_actions.wait_for_element_present(self.driver, how, selector, timeout)1169 try:1170 selector = self.convert_to_css_selector(how, selector)1171 except Exception:1172 # Don't run action if can't convert to CSS_Selector for JavaScript1173 raise WebDriverException(1174 "Exception: Could not convert {how=how}({selector}) to CSS_SELECTOR!"1175 )1176 selector = re.escape(selector)1177 selector = shared.escape_quotes_if_needed(selector)1178 script = """var $elm = document.querySelector('%s');1179 $val = window.getComputedStyle($elm).getPropertyValue('%s');1180 return $val;""" % (1181 selector,1182 property,1183 )1184 value = self.execute_script(script)1185 if value is not None:1186 return value1187 else:1188 return "" # Return an empty string if the property doesn't exist1189 def get_image_url(1190 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1191 timeout: OptionalInt = None1192 ):1193 """ Extracts the URL from an image element on the page. """1194 self.__check_scope__()1195 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)1196 return self.get_attribute(how, selector, "src", timeout)1197 def find_elements(1198 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1), limit=01199 ) -> List[WebElement]:1200 """Returns a list of matching WebElements.1201 Elements could be either hidden or visible on the page.1202 If "limit" is set and > 0, will only return that many elements."""1203 self.wait_for_ready_state_complete()1204 time.sleep(0.05)1205 elements = element_actions.find_elements(self.driver, how, selector)1206 if 0 < limit < len(elements):1207 elements = elements[:limit]1208 return elements1209 @validate_arguments1210 def find_visible_elements(1211 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1), limit=0):1212 """Returns a list of matching WebElements that are visible.1213 If "limit" is set and > 0, will only return that many elements."""1214 self.__check_scope__()1215 self.wait_for_ready_state_complete()1216 time.sleep(0.05)1217 v_elems = page_actions.find_visible_elements(self.driver, selector, by)1218 if limit and limit > 0 and len(v_elems) > limit:1219 v_elems = v_elems[:limit]1220 return v_elems1221 @validate_arguments1222 def click_visible_elements(1223 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1224 limit: int = 0, timeout: OptionalInt = None1225 ) -> None:1226 """Finds all matching page elements and clicks visible ones in order.1227 If a click reloads or opens a new page, the clicking will stop.1228 If no matching elements appear, an Exception will be raised.1229 If "limit" is set and > 0, will only click that many elements.1230 Also clicks elements that become visible from previous clicks.1231 Works best for actions such as clicking all checkboxes on a page.1232 """1233 self.__check_scope__()1234 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)1235 self.wait_for_element_present(how, selector, timeout=timeout)1236 elements = self.find_elements(how, selector)1237 if self.driver.capabilities.get("browserName") == "safari":1238 if not limit:1239 limit = 01240 num_elements = len(elements)1241 if num_elements == 0:1242 raise Exception(1243 "No matching elements found for selector {%s}!" % selector1244 )1245 elif num_elements < limit or limit == 0:1246 limit = num_elements1247 css_selector = self.convert_to_css_selector(selector, by=by)1248 last_css_chunk = css_selector.split(" ")[-1]1249 if ":" in last_css_chunk:1250 self.__js_click_all(css_selector)1251 self.wait_for_ready_state_complete()1252 return1253 else:1254 for i in range(1, limit + 1):1255 new_selector = css_selector + ":nth-of-type(%s)" % str(i)1256 if self.is_element_visible(new_selector):1257 self.__js_click(new_selector)1258 self.wait_for_ready_state_complete()1259 return1260 pre_action_url = self.driver.current_url1261 pre_window_count = len(self.driver.window_handles)1262 click_count = 01263 for element in elements:1264 if limit and 0 < limit <= click_count:1265 return1266 try:1267 if element.is_displayed():1268 self.__scroll_to_element(element)1269 element.click()1270 click_count += 11271 self.wait_for_ready_state_complete()1272 except ElementClickInterceptedException:1273 continue1274 except (StaleElementReferenceException, ElementNotInteractableException):1275 self.wait_for_ready_state_complete()1276 time.sleep(0.12)1277 try:1278 if element.is_displayed():1279 self.__scroll_to_element(element)1280 element.click()1281 click_count += 11282 self.wait_for_ready_state_complete()1283 except (StaleElementReferenceException, ElementNotInteractableException):1284 latest_window_count = len(self.driver.window_handles)1285 if (1286 latest_window_count > pre_window_count1287 and (1288 self.recorder_mode1289 or (1290 settings.SWITCH_TO_NEW_TABS_ON_CLICK1291 and self.driver.current_url == pre_action_url1292 )1293 )1294 ):1295 self.__switch_to_newest_window_if_not_blank()1296 return # Probably on new page / Elements are all stale1297 latest_window_count = len(self.driver.window_handles)1298 if (1299 latest_window_count > pre_window_count1300 and (1301 self.recorder_mode1302 or (1303 settings.SWITCH_TO_NEW_TABS_ON_CLICK1304 and self.driver.current_url == pre_action_url1305 )1306 )1307 ):1308 self.__switch_to_newest_window_if_not_blank()1309 def click_nth_visible_element(1310 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1311 number: int = 0, timeout: OptionalInt = None1312 ):1313 """Finds all matching page elements and clicks the nth visible one.1314 Example: self.click_nth_visible_element('[type="checkbox"]', 5)1315 (Clicks the 5th visible checkbox on the page.)"""1316 self.__check_scope__()1317 timeout = self.get_timeout(timeout, constants.SMALL_TIMEOUT)1318 self.wait_for_ready_state_complete()1319 self.wait_for_element_present(how, selector, timeout=timeout)1320 elements = self.find_visible_elements(how, selector)1321 if len(elements) < number:1322 raise WebDriverException(1323 f"Not enough matching {selector} elements of type {how.upper()} to "1324 f"click number {number}!"1325 )1326 number = number - 11327 if number < 0:1328 number = 01329 element = elements[number]1330 pre_action_url = self.driver.current_url1331 pre_window_count = len(self.driver.window_handles)1332 try:1333 self.__scroll_to_element(element)1334 element.click()1335 except (StaleElementReferenceException, ElementNotInteractableException):1336 time.sleep(0.12)1337 self.wait_for_ready_state_complete()1338 self.wait_for_element_present(how, selector, timeout=timeout)1339 elements = self.find_visible_elements(how, selector)1340 if len(elements) < number:1341 raise WebDriverException(1342 f"Not enough matching {selector} elements of type {how} to click number {number}!"1343 )1344 number = number - 11345 if number < 0:1346 number = 01347 element = elements[number]1348 element.click()1349 latest_window_count = len(self.driver.window_handles)1350 if (1351 latest_window_count > pre_window_count1352 and (1353 self.recorder_mode1354 or (1355 settings.SWITCH_TO_NEW_TABS_ON_CLICK1356 and self.driver.current_url == pre_action_url1357 )1358 )1359 ):1360 self.__switch_to_newest_window_if_not_blank()1361 def click_if_visible(1362 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1)1363 ) -> None:1364 """If the page selector exists and is visible, clicks on the element.1365 This method only clicks on the first matching element found.1366 (Use click_visible_elements() to click all matching elements.)"""1367 self.wait_for_ready_state_complete()1368 if self.is_element_visible(how, selector):1369 self.click(how, selector)1370 def click_active_element(self):1371 self.wait_for_ready_state_complete()1372 pre_action_url = self.driver.current_url1373 pre_window_count = len(self.driver.window_handles)1374 self.execute_script("document.activeElement.click();")1375 latest_window_count = len(self.driver.window_handles)1376 if (1377 latest_window_count > pre_window_count1378 and (1379 self.recorder_mode1380 or (1381 settings.SWITCH_TO_NEW_TABS_ON_CLICK1382 and self.driver.current_url == pre_action_url1383 )1384 )1385 ):1386 self.__switch_to_newest_window_if_not_blank()1387 if settings.WAIT_FOR_RSC_ON_CLICKS:1388 self.wait_for_ready_state_complete()1389 else:1390 # A smaller subset of self.wait_for_ready_state_complete()1391 self.wait_for_angularjs(timeout=settings.MINI_TIMEOUT)1392 if self.driver.current_url != pre_action_url:1393 self.__ad_block_as_needed()1394 if self.demo_mode:1395 if self.driver.current_url != pre_action_url:1396 self._demo_mode_pause_if_active()1397 else:1398 self._demo_mode_pause_if_active(tiny=True)1399 elif self.slow_mode:1400 self._slow_mode_pause_if_active()1401 @validate_arguments1402 def is_checked(1403 self, how: SeleniumBy, selector: str = Field(..., strict=True, min_length=1),1404 timeout: OptionalInt = None1405 ):1406 """Determines if a checkbox or a radio button element is checked.1407 Returns True if the element is checked....

Full Screen

Full Screen

webdrivertest.py

Source:webdrivertest.py Github

copy

Full Screen

...118 except WebDriverException:119 pass120 if not active_window:121 raise NoSuchWindowException("Active window was already closed!")122 def __ad_block_as_needed(self):123 """124 This is an internal method for handling ad-blocking.125 Use "pytest --ad-block" to enable this during tests.126 When not Chromium or in headless mode, use the hack.127 """128 ad_block_on = self.config.getoption("ad_block_on", False)129 headless = self.config.getoption("headless", False)130 if ad_block_on and (headless or not self.is_chromium()):131 # -- Chromium browsers in headed mode use the extension instead132 current_url, httpx_url = self.get_current_url()133 if not current_url == self.__last_page_load_url:134 if is_element_present(self.driver, By.CSS_SELECTOR, "iframe"):135 self.ad_block()136 self.__last_page_load_url = current_url137 def __highlight_with_jquery(self, selector, loops, o_bs):138 self.wait_for_ready_state_complete()139 highlight_with_jquery(self.driver, selector, loops, o_bs)140 # def __make_css_match_first_element_only(self, selector):141 # logger.trace("Only get the first match of -> {}", selector)142 # return make_css_match_first_element_only(selector)143 # def __demo_mode_pause_if_active(self, tiny=False):144 # if self.config.getoption("demo_mode", False):145 # wait_time = settings.DEFAULT_DEMO_MODE_TIMEOUT146 # if self.config.getoption("demo_sleep", None):147 # wait_time = float(self.config.getoption("demo_sleep"))148 # if not tiny:149 # time.sleep(wait_time)150 # else:151 # time.sleep(wait_time / 3.4)152 # elif self.config.getoption("slow_mode", False):153 # self.__slow_mode_pause_if_active()154 # def __slow_mode_pause_if_active(self):155 # if self.config.getoption("slow_mode", False):156 # wait_time = settings.DEFAULT_DEMO_MODE_TIMEOUT157 # if self.config.getoption("demo_mode", False):158 # wait_time = float(self.config.getoption("demo_sleep"))159 # time.sleep(wait_time)160 # def __demo_mode_scroll_if_active(self, how: SeleniumBy, selector: str):161 # if self.config.getoption("demo_mode", False):162 # self.slow_scroll_to(how, selector)163 #164 # def __demo_mode_highlight_if_active(self, how: SeleniumBy, selector: str):165 # if self.config.getoption("demo_mode", False):166 # self.highlight(how, selector)167 # if self.config.getoption("slow_mode", False):168 # time.sleep(0.08)169 # element = self.wait_for_element_visible(how, selector, timeout=constants.SMALL_TIMEOUT)170 # try: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:...

Full Screen

Full Screen

_webdriver_base_test.py

Source:_webdriver_base_test.py Github

copy

Full Screen

...118 js_utils.wait_for_ready_state_complete(self.driver, timeout)119 self.wait_for_angularjs(timeout=constants.MINI_TIMEOUT)120 if self.config.getoption("js_checking_on"):121 self.assert_no_js_errors()122 self.__ad_block_as_needed()123 return True124 def wait_for_angularjs(self, timeout: OptionalInt = None, **kwargs):125 """Waits for Angular components of the page to finish loading.126 Returns True when the method completes.127 """128 self.__check_scope__()129 timeout = self.get_timeout(timeout, constants.MINI_TIMEOUT)130 js_utils.wait_for_angularjs(self.driver, timeout, **kwargs)131 return True132 def execute_script(self, script: str, *args) -> Any:133 self.__check_scope__()134 self.__check_browser__()135 return self.driver.execute_script(script, *args)136 def execute_async_script(self, script, timeout=None) -> Any:...

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