Best Python code snippet using SeleniumBase
webdrivertest.py
Source:webdrivertest.py
...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")...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!