Best Python code snippet using toolium_python
browser.py
Source:browser.py
...75 return webdriver.Chrome(chrome_options=opt)76 except WebDriverException as error:77 proxy.close()78 raise Exception(str(error))79def _setup_firefox(proxy):80 """Setup the Mozilla geckodriver to run as minimally as possible"""81 opt = webdriver.FirefoxOptions()82 opt.add_argument("-headless")83 opt.add_argument("-private")84 opt.add_argument("-safe-mode")85 opt.add_argument("-no-remote")86 pro = webdriver.FirefoxProfile()87 # Instruct Firefox to proxy all requests via our previously created proxy server.88 pro.set_proxy(webdriver.Proxy({"httpProxy": proxy.proxy, "sslProxy": proxy.proxy}))89 # Accept untrusted certs.90 pro.accept_untrusted_certs = True91 try:92 return webdriver.Firefox(firefox_profile=pro, firefox_options=opt, log_path="/dev/null")93 except WebDriverException as error:94 proxy.close()95 raise Exception(str(error))96def _setup_proxy(headers):97 """Setup the BUP HTTP proxy used to capture HAR data."""98 proxy = None99 # Setup the proxy server used to capture har data.100 try:101 proxy = Proxy("localhost:8080")102 proxy.create_har()103 # The proxy client already does type checking to ensure that the passed headers to be104 # injected is a dictionary. Simply re-raise the exception if that is not the case.105 try:106 proxy.inject_headers(headers)107 except TypeError:108 proxy.close()109 raise110 except ProxyClientError as error:111 if proxy is not None:112 proxy.close()113 raise Exception(f"Failed to create a new har due to the following error: {str(error)}")114 return proxy115def browser_request(url, **kwargs):116 """Execute a browser emulated HTTP request.117 Attempt to load a provided webpage via a specified Browser, and return HAR data collected118 by a newly created proxy server.119 Args:120 url (str) : The webpage URL to attempt to load via the emulated browser.121 **driver (str) : The browser driver to use in the request. Defaults to "chrome".122 **headers (dict) : A key/value dict of HTTP request headers to inject. Defaults to None.123 Returns:124 dict: Returns a dictionary object with test results.125 """126 driver = kwargs.get("driver", "chrome").lower()127 headers = kwargs.get("headers", None)128 headers = headers if headers is not None else {}129 failed = True130 proxy = _setup_proxy(headers)131 if driver == "chrome":132 webdriver_ = _setup_chrome(proxy)133 elif driver == "firefox":134 webdriver_ = _setup_firefox(proxy)135 else:136 proxy.close()137 raise Exception(f"Provided driver of '{driver}' is not supported.")138 webdriver_.set_page_load_timeout(constants.WEBPAGE_LOAD_TIMEOUT)139 har = {"driver": driver, "child": []}140 try:141 webdriver_.get(url)142 except Exception as error: # pylint: disable=broad-except143 # Firefox causes Selenium to throw an unknown error when a load failure occurs,144 # such as DNS resolution and connection failures.145 if driver == "firefox" and "Reached error page" in str(error):146 pass147 else:148 proxy.close()...
webdrivers.py
Source:webdrivers.py
...83 WebDriver.add_script = _add_script84 # launch Chrome85 driver = webdriver.Chrome(options=chrome_options, desired_capabilities=capabilities)86 return driver87def _setup_firefox(config: Config, _profile_path: Path = None) -> WebDriver:88 assert is_driver_installed(Drivers.FIREFOX)89 assert is_driver_installed(Drivers.GECKODRIVER)90 log_driver_version("Firefox version", Drivers.FIREFOX)91 log_driver_version("Geckodriver version", Drivers.GECKODRIVER)92 firefox_profile = webdriver.FirefoxProfile()93 firefox_options = webdriver.FirefoxOptions()94 browser = config.browser95 # Disable security96 firefox_options.add_argument("-safe-mode")97 firefox_profile.set_preference("browser.link.open_newwindow", 3)98 firefox_profile.set_preference("browser.link.open_newwindow.restriction", 0)99 firefox_profile.set_preference("media.volume_scale", "0.0")100 firefox_options.headless = browser.headless101 if browser.proxy:102 address = browser.proxy.split(":")103 firefox_profile.set_preference("network.proxy.http", address[0])104 firefox_profile.set_preference("network.proxy.http_port", address[1])105 if browser.enable_mhtml:106 # TODO107 logger.critical("Firefox does not currently support MHTML")108 assert False109 if "pixelRatio" in browser and browser.pixelRatio != 0:110 # TODO111 logger.error("Firefox does not currently support custom pixelratio")112 if "useragent" in browser:113 firefox_profile.set_preference("general.useragent.override", browser.useragent)114 def _add_script(driver: WebDriver, script_path: str):115 send(driver, "Page.addScriptToEvaluateOnNewDocument", {"source": script_path})116 WebDriver.add_script = _add_script117 # TODO No support to output console logs for geckodriver118 driver = webdriver.Firefox(options=firefox_options, firefox_profile=firefox_profile)119 # Screen size (we can't set viewport size as for Chrome so we adjust screen size)120 if "width" in browser and "height" in browser:121 driver.set_window_size(browser.width, browser.height)122 return driver123def setup_driver(config: Config, profile_path: Path = None, preload_callbacks: Iterable[Path] = None) -> WebDriver:124 """125 Creates a WebDriver object with the given configuration.126 :param: configuration Configuration dictionary127 :return: A WebDriver instance128 """129 driver = None130 name = config.browser.browser.lower()131 if name == "chrome":132 driver = _setup_chrome(config=config, profile_path=profile_path)133 elif name == "firefox":134 driver = _setup_firefox(config=config, _profile_path=profile_path)135 else:136 raise NotImplementedError(f"Uninmplemented browser type given to setup_driver: {config.browser.browser}")137 preload_callbacks = preload_callbacks or []138 for cb in preload_callbacks:139 driver.add_script(str(cb))140 return driver141def send(driver: WebDriver, cmd: str, params: dict = None) -> int:142 """143 Send command to the webdriver, return resulting status code.144 """145 # pylint: disable=protected-access146 params = params or {}147 resource = f"/session/{driver.session_id}/chromium/send_command_and_get_result"148 url = driver.command_executor._url + resource...
baseextractor.py
Source:baseextractor.py
...34 self.server.start({'log_path': LOG_DIR, 'log_file': 'server.log'})35 self.proxy = self.server.create_proxy()36 # setup webdriver37 if browser == 'firefox':38 self.driver = self._setup_firefox()39 elif browser == 'chrome':40 self.driver = self._setup_chrome()41 else:42 logging.error(f'{browser} not supported. Use \'firefox\' or \'chrome\'')43 raise NotImplementedError44 # we need to call the superclass, since we are inheriting from threading.Thread45 super(BaseExtractor, self).__init__()46 def _setup_chrome(self):47 options = webdriver.ChromeOptions()48 if self.capture_har:49 options.add_argument(f'--proxy-server=127.0.0.1:{self.proxy.port}')50 options.add_argument('--mute-audio')51 return webdriver.Chrome(52 executable_path=config.CHROME_EXECUTABLE,53 chrome_options=options54 )55 def _setup_firefox(self):56 profile = webdriver.FirefoxProfile()57 if self.capture_har:58 profile.set_proxy(self.proxy.selenium_proxy())59 return webdriver.Firefox(60 firefox_profile=profile,61 executable_path=config.FIREFOX_EXECUTABLE,62 log_path=os.path.join(LOG_DIR, 'geckodriver.log')63 )64 def __enter__(self):65 """support for with statement to cleanup stuff..."""66 # todo does this even work with threads?67 return self68 def __exit__(self, exc_type, exc_val, exc_tb):69 logging.info("Cleaning up...")...
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!!