{"record":{"id":"277139240ba0783d","repo":"D4Vinci/Scrapling","slug":"context-manager-has-been-closed-277139","errorCode":null,"errorMessage":"Context manager has been closed","messagePattern":"Context manager has been closed","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"scrapling/engines/_browsers/_stealth.py","lineNumber":210,"sourceCode":"        :param page_setup: A function that takes the `page` object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.\n        :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by `google_search` takes priority over the referer set here if used together._\n        :param disable_resources: Drop requests for unnecessary resources for a speed boost.\n            Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.\n        :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``\"example.com\"`` blocks ``\"sub.example.com\"`` too).\n        :param wait_selector: Wait for a specific CSS selector to be in a specific state.\n        :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`.\n        :param network_idle: Wait for the page until there are no network connections for at least 500 ms.\n        :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.\n        :param solve_cloudflare: Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.\n        :param selector_config: The arguments that will be passed in the end while creating the final Selector's class.\n        :param proxy: Static proxy to override rotator and session proxy. A new browser context will be created and used with it.\n        :return: A `Response` object.\n        \"\"\"\n        static_proxy = kwargs.pop(\"proxy\", None)\n\n        params = _validate(kwargs, self, StealthConfig)\n        if not self._is_alive:  # pragma: no cover\n            raise RuntimeError(\"Context manager has been closed\")\n\n        request_headers_keys = {h.lower() for h in params.extra_headers.keys()} if params.extra_headers else set()\n        referer = (\n            \"https://www.google.com/\" if (params.google_search and \"referer\" not in request_headers_keys) else None\n        )\n\n        for attempt in range(self._config.retries):\n            proxy: Optional[ProxyType] = None\n            if self._config.proxy_rotator and static_proxy is None:\n                proxy = self._config.proxy_rotator.get_proxy()\n            else:\n                proxy = static_proxy\n\n            with self._page_generator(\n                params.timeout, params.extra_headers, params.disable_resources, proxy, params.blocked_domains\n            ) as page_info:\n                final_response: List = [None]\n                xhr_captured: List = []","sourceCodeStart":192,"sourceCodeEnd":228,"githubUrl":"https://github.com/D4Vinci/Scrapling/blob/5d213a2d4764002bfc4fed33c32fe09fa8b0bf7f/scrapling/engines/_browsers/_stealth.py#L192-L228","documentation":"Raised by StealthySession.fetch() when the session's `_is_alive` flag is False, i.e. the underlying browser context was never started or has already been closed. fetch() can only run while the session context manager is open.","triggerScenarios":"Calling fetch() after the `with StealthySession(...)` block exited, calling fetch() before start(), or after stop()/an internal crash tore down the browser.","commonSituations":"Storing the session and calling fetch() later in a different function/scope after the context manager closed, or an earlier exception in __exit__ leaving the session dead.","solutions":["Move all fetch() calls inside the `with StealthySession(...) as session:` block","Ensure start() succeeded before fetching and that no prior error closed the session","For long-lived usage, keep the context manager open for the whole scraping run and close it in a finally block"],"exampleFix":"// before\nwith StealthySession() as s:\n    pass\nresp = s.fetch('https://example.com')  # RuntimeError\n\n// after\nwith StealthySession() as s:\n    resp = s.fetch('https://example.com')","handlingStrategy":"validation","validationCode":"if not session._is_alive:\n    raise RuntimeError('session closed; reopen before fetching')\nresp = session.fetch(url)","typeGuard":"def can_fetch(s) -> bool:\n    return bool(getattr(s, '_is_alive', False))","tryCatchPattern":"try:\n    resp = session.fetch(url)\nexcept RuntimeError as e:\n    if 'closed' in str(e):\n        # reopen a new session and retry once\n        with StealthySession() as s2:\n            resp = s2.fetch(url)\n    else:\n        raise","preventionTips":["Keep every fetch() inside the `with` block; structure code so the session outlives its fetches","If managing lifecycle manually, guard fetch with `if not session._is_alive: restart`","Gather/cancel background tasks before the context manager exits"],"tags":["session-lifecycle","stealth","sync","usage-order"],"backgroundTag":null,"analyzedSha":"5d213a2d4764002bfc4fed33c32fe09fa8b0bf7f","analyzedAt":"2026-08-14T22:23:09.440Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}