Best Python code snippet using toolium_python
browser.py
Source:browser.py  
...35            entry["timings"][key] = float(entry["timings"][key])36        entry["timings"]["total"] = float(entry["time"])37        formatted_har.append(entry)38    return formatted_har39def _setup_chrome(proxy):40    """Setup the Google chromedriver to run as minimally as possible"""41    opt = webdriver.ChromeOptions()42    # Setup Chrome options to run as minimal as possible.43    opt.add_argument("--headless")44    opt.add_argument("--incognito")45    # Instruct Chrome to proxy all requests via our previously created proxy server.46    opt.add_argument(f"--proxy-server={proxy.proxy}")47    opt.add_argument("--no-sandbox")48    opt.add_argument("--disable-background-networking")49    opt.add_argument("--enable-features=NetworkService,NetworkServiceInProcess")50    opt.add_argument("--disable-background-timer-throttling")51    opt.add_argument("--disable-backgrounding-occluded-windows")52    opt.add_argument("--disable-breakpad")53    opt.add_argument("--disable-client-side-phishing-detection")54    opt.add_argument("--disable-default-apps")55    opt.add_argument("--disable-extensions")56    opt.add_argument("--disable-features=site-per-process,TranslateUI,BlinkGenPropertyTrees")57    opt.add_argument("--disable-hang-monitor")58    opt.add_argument("--disable-ipc-flooding-protection")59    opt.add_argument("--disable-popup-blocking")60    opt.add_argument("--disable-prompt-on-repost")61    opt.add_argument("--disable-renderer-backgrounding")62    opt.add_argument("--disable-sync")63    opt.add_argument("--force-color-profile=srgb")64    opt.add_argument("--metrics-recording-only")65    opt.add_argument("--no-first-run")66    opt.add_argument("--safebrowsing-disable-auto-update")67    opt.add_argument("--enable-automation")68    opt.add_argument("--password-store=basic")69    opt.add_argument("--use-mock-keychain")70    opt.add_argument("--hide-scrollbars")71    opt.add_argument("--mute-audio")72    # Accept untrusted certs.73    opt.add_argument("--ignore-certificate-errors")74    try: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            pass...ExtendedSelenium.py
Source:ExtendedSelenium.py  
...15    def __init__(self, *args, **kwargs):16        super().__init__(*args, **kwargs)17        self._chrome_ready = False18    19    def _setup_chrome(self):20        if self._chrome_ready:21            return22        23        cdm = ChromeDriverManager(link_path="AUTO")24        cdm.download_and_install()25        self._chrome_ready = True26                    27    @keyword28    def open_chrome_site(self, url, headless=False, **kwargs):29        self._setup_chrome()30        31        options = webdriver.ChromeOptions()32        if self.USER_DATA_PATH:33            options.add_argument(f"user-data-dir={self.USER_DATA_PATH}")34        if headless:35            options.add_argument("--headless")36        caps = DesiredCapabilities.CHROME.copy()37        caps["acceptInsecureCerts"] = True38        self.open_browser(39            url=url,40            options=options,41            desired_capabilities=caps,42            browser="chrome",43            **kwargs...baseextractor.py
Source:baseextractor.py  
...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,...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!!
