How to use bring_active_window_to_front method in SeleniumBase

Best Python code snippet using SeleniumBase

webdriver_test.py

Source:webdriver_test.py Github

copy

Full Screen

...2456 self.__check_scope__()2457 self.driver = driver2458 if self.driver in self.__driver_browser_map:2459 self.browser = self.__driver_browser_map[self.driver]2460 self.bring_active_window_to_front()2461 def switch_to_default_driver(self):2462 """ Sets self.driver to the default/original driver. """2463 self.__check_scope__()2464 self.driver = self._default_driver2465 if self.driver in self.__driver_browser_map:2466 self.browser = self.__driver_browser_map[self.driver]2467 self.bring_active_window_to_front()2468 def save_screenshot(2469 self, name, folder=None, selector=None, by=By.CSS_SELECTOR2470 ):2471 """2472 Saves a screenshot of the current page.2473 If no folder is specified, uses the folder where pytest was called.2474 The screenshot will include the entire page unless a selector is given.2475 If a provided selector is not found, then takes a full-page screenshot.2476 If the folder provided doesn't exist, it will get created.2477 The screenshot will be in PNG format: (*.png)2478 """2479 self.wait_for_ready_state_complete()2480 if selector and by:2481 selector, by = self.__recalculate_selector(selector, by)2482 if page_actions.is_element_present(self.driver, selector, by):2483 return page_actions.save_screenshot(2484 self.driver, name, folder, selector, by2485 )2486 return page_actions.save_screenshot(self.driver, name, folder)2487 def save_screenshot_to_logs(2488 self, name=None, selector=None, by=By.CSS_SELECTOR2489 ):2490 """Saves a screenshot of the current page to the "latest_logs" folder.2491 Naming is automatic:2492 If NO NAME provided: "_1_screenshot.png", "_2_screenshot.png", etc.2493 If NAME IS provided, it becomes: "_1_name.png", "_2_name.png", etc.2494 The screenshot will include the entire page unless a selector is given.2495 If a provided selector is not found, then takes a full-page screenshot.2496 (The last_page / failure screenshot is always "screenshot.png")2497 The screenshot will be in PNG format."""2498 self.wait_for_ready_state_complete()2499 test_logpath = os.path.join(self.log_path, self.__get_test_id())2500 self.__create_log_path_as_needed(test_logpath)2501 if name:2502 name = str(name)2503 self.__screenshot_count += 12504 if not name or len(name) == 0:2505 name = "_%s_screenshot.png" % self.__screenshot_count2506 else:2507 pre_name = "_%s_" % self.__screenshot_count2508 if len(name) >= 4 and name[-4:].lower() == ".png":2509 name = name[:-4]2510 if len(name) == 0:2511 name = "screenshot"2512 name = "%s%s.png" % (pre_name, name)2513 if selector and by:2514 selector, by = self.__recalculate_selector(selector, by)2515 if page_actions.is_element_present(self.driver, selector, by):2516 return page_actions.save_screenshot(2517 self.driver, name, test_logpath, selector, by2518 )2519 return page_actions.save_screenshot(self.driver, name, test_logpath)2520 def save_page_source(self, name, folder=None):2521 """Saves the page HTML to the current directory (or given subfolder).2522 If the folder specified doesn't exist, it will get created.2523 @Params2524 name - The file name to save the current page's HTML to.2525 folder - The folder to save the file to. (Default = current folder)2526 """2527 self.wait_for_ready_state_complete()2528 return page_actions.save_page_source(self.driver, name, folder)2529 # def save_cookies(self, name="cookies.txt"):2530 # """ Saves the page cookies to the "saved_cookies" folder. """2531 # self.wait_for_ready_state_complete()2532 # cookies = self.driver.get_cookies()2533 # json_cookies = json.dumps(cookies)2534 # if name.endswith("/"):2535 # raise Exception("Invalid filename for Cookies!")2536 # if "/" in name:2537 # name = name.split("/")[-1]2538 # if len(name) < 1:2539 # raise Exception("Filename for Cookies is too short!")2540 # if not name.endswith(".txt"):2541 # name = name + ".txt"2542 # folder = constants.SavedCookies.STORAGE_FOLDER2543 # abs_path = os.path.abspath(".")2544 # file_path = abs_path + "/%s" % folder2545 # if not os.path.exists(file_path):2546 # os.makedirs(file_path)2547 # cookies_file_path = "%s/%s" % (file_path, name)2548 # cookies_file = codecs.open(cookies_file_path, "w+", encoding="utf-8")2549 # cookies_file.writelines(json_cookies)2550 # cookies_file.close()2551 #2552 # def load_cookies(self, name="cookies.txt"):2553 # """ Loads the page cookies from the "saved_cookies" folder. """2554 # self.wait_for_ready_state_complete()2555 # if name.endswith("/"):2556 # raise Exception("Invalid filename for Cookies!")2557 # if "/" in name:2558 # name = name.split("/")[-1]2559 # if len(name) < 1:2560 # raise Exception("Filename for Cookies is too short!")2561 # if not name.endswith(".txt"):2562 # name = name + ".txt"2563 # folder = constants.SavedCookies.STORAGE_FOLDER2564 # abs_path = os.path.abspath(".")2565 # file_path = abs_path + "/%s" % folder2566 # cookies_file_path = "%s/%s" % (file_path, name)2567 # json_cookies = None2568 # with open(cookies_file_path, "r") as f:2569 # json_cookies = f.read().strip()2570 # cookies = json.loads(json_cookies)2571 # for cookie in cookies:2572 # if "expiry" in cookie:2573 # del cookie["expiry"]2574 # self.driver.add_cookie(cookie)2575 #2576 # def delete_all_cookies(self):2577 # """Deletes all cookies in the web browser.2578 # Does NOT delete the saved cookies file."""2579 # self.wait_for_ready_state_complete()2580 # self.driver.delete_all_cookies()2581 #2582 # def delete_saved_cookies(self, name: str = "cookies.txt"):2583 # """Deletes the cookies file from the "saved_cookies" folder.2584 # Does NOT delete the cookies from the web browser."""2585 # self.wait_for_ready_state_complete()2586 # if name.endswith("/"):2587 # raise Exception("Invalid filename for Cookies!")2588 # if "/" in name:2589 # name = name.split("/")[-1]2590 # if len(name) < 1:2591 # raise Exception("Filename for Cookies is too short!")2592 # if not name.endswith(".txt"):2593 # name = name + ".txt"2594 # folder = constants.SavedCookies.STORAGE_FOLDER2595 # abs_path = os.path.abspath(".")2596 # file_path = abs_path + "/%s" % folder2597 # cookies_file_path = "%s/%s" % (file_path, name)2598 # if os.path.exists(cookies_file_path):2599 # if cookies_file_path.endswith(".txt"):2600 # os.remove(cookies_file_path)2601 def install_addon(self, xpi_file: FilePath):2602 """Installs a Firefox add-on instantly at run-time.2603 @Params2604 xpi_file - A file archive in .xpi format.2605 """2606 self.wait_for_ready_state_complete()2607 if self.driver.capabilities.get("browseName") != "firefox":2608 raise Exception(2609 "install_addon(xpi_file) is for Firefox ONLY!\n"2610 "To load a Chrome extension, use the comamnd-line:\n"2611 "--extension_zip=CRX_FILE OR --extension_dir=DIR"2612 )2613 xpi_path = os.path.abspath(xpi_file)2614 self.driver.install_addon(xpi_path, temporary=True)2615 def activate_demo_mode(self):2616 self.demo_mode = True2617 def deactivate_demo_mode(self):2618 self.demo_mode = False2619 def activate_design_mode(self):2620 # Activate Chrome's Design Mode, which lets you edit a site directly.2621 # See: https://twitter.com/sulco/status/11775591505633443842622 self.wait_for_ready_state_complete()2623 script = """document.designMode = 'on';"""2624 self.execute_script(script)2625 def deactivate_design_mode(self):2626 # Deactivate Chrome's Design Mode.2627 self.wait_for_ready_state_complete()2628 script = """document.designMode = 'off';"""2629 self.execute_script(script)2630 def bring_active_window_to_front(self):2631 """Brings the active browser window to the front.2632 This is useful when multiple drivers are being used."""2633 self.__check_scope__()2634 try:2635 if not js_utils.is_in_frame():2636 # Only bring the window to the front if not in a frame2637 # because the driver resets itself to default content.2638 self.switch_to_window(self.driver.current_window_handle)2639 except Exception:2640 pass2641 def bring_to_front(self, selector, by=By.CSS_SELECTOR):2642 """Updates the Z-index of a page element to bring it into view.2643 Useful when getting a WebDriverException, such as the one below:2644 { Element is not clickable at point (#, #)....

Full Screen

Full Screen

webdrivertest.py

Source:webdrivertest.py Github

copy

Full Screen

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

Full Screen

Full Screen

presearch.py

Source:presearch.py Github

copy

Full Screen

...217 f"delay {np.round(delayseconds, 2)} seconds ... {i}/{searchcounts}"218 )219 time.sleep(delayseconds)220 # self.go_back()221 self.bring_active_window_to_front()222 # self.switch_to_window(self.driver.window_handles[-2])223 self.delay_sendkey()224 self._print(f"Done ... {searchcounts=}")225 def test_basic(self):226 # self._print(f"self.driver:{dir(self.driver)}")227 old_window = self.driver.window_handles228 self.open_new_tab()229 self.prepare()230 url = "https://www.presearch.org/"231 url2 = self.restarturl232 logined_str = "//*/div[1]/span[2]"233 need_login_str = 'div:contains("Register or Login")'234 try:235 self.open(url)...

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