def new_browser(data: Classes.Data, page: Classes.Page = None, debug: bool = False, interceptor=None, remove_alerts: bool = True): """ This function creates a new browser instance with a new session. @param data: The data object of the program. @type data: Classes.Data @param page: The page to be opened with the new browser to initialize cookies and get page (optional). @type page: Classes.Page @param debug: In case of debugging, in case of True the chrome window will appear. @type debug: bool @param interceptor: A pointer to an interceptor function. @type interceptor: a function @param remove_alerts: If True, the browser will remove every alert on `get` and `refresh` methods. @type remove_alerts: bool @return: Chrome web driver object. @rtype: Classes.Browser """ if not data.driver: # There is no driver file path. raise Exception("There is no driver file path", "\t") options = webdriver.ChromeOptions() if not debug: # If it's not debug, the browser will be headless. options.headless = True options.add_experimental_option("excludeSwitches", ["enable-logging"]) try: browser = Classes.Browser(data.driver, options, remove_alerts) except Exception as e: # In case of failure, we need to try again return new_browser(data, page, debug, interceptor) def default_interceptor(request: selenium_request.Request): """ Inner function that acts like a proxy, it removes any requests we don't want. @param request: The current request @type request: selenium_request.Request @return: None """ # Block PNG, JPEG and GIF images. if request.path.endswith(('.png', '.jpg', '.gif')): request.abort() # Abort the unwanted request. # Setting up request interceptor. if interceptor: browser.request_interceptor = interceptor else: browser.request_interceptor = default_interceptor # Setting long timeout. browser.set_page_load_timeout(60) if page: # If a page was specified. if page.parent: browser.get(page.parent.url) # Getting parent URL. else: browser.get(page.url) # Getting current URL. for cookie in page.cookies: # Adding cookies. browser.add_cookie(cookie) # Getting the page again, with the loaded cookies. browser.get(page.url) return browser