{"record":{"id":"a78beb97d3f55a9b","repo":"SeleniumHQ/selenium","slug":"cannot-write-storage-state-to-file-path-e","errorCode":null,"errorMessage":"Cannot write storage state to {file_path}: {e}","messagePattern":"Cannot write storage state to (.+?): (.+?)","errorType":"exception","errorClass":"OSError","httpStatus":null,"severity":"error","filePath":"py/selenium/webdriver/common/api_request_context.py","lineNumber":604,"sourceCode":"\n    def get_storage_state(self, path: str | pathlib.Path | None = None) -> dict[str, Any]:\n        \"\"\"Export the current browser cookies as a storage state dict.\n\n        Args:\n            path: Optional file path to save the storage state as JSON.\n\n        Returns:\n            A dict with a \"cookies\" key containing the browser cookies.\n        \"\"\"\n        cookies = self._driver.get_cookies()\n        state: dict[str, Any] = {\"cookies\": cookies}\n        if path is not None:\n            file_path = pathlib.Path(path)\n            try:\n                with open(file_path, \"w\") as f:\n                    json.dump(state, f, indent=2)\n            except OSError as e:\n                raise OSError(f\"Cannot write storage state to {file_path}: {e}\") from e\n        return state\n\n    def _get_cookies_for_request(self, url: str) -> list[dict]:\n        \"\"\"Get matching browser cookies for the request URL.\"\"\"\n        try:\n            browser_cookies = self._driver.get_cookies()\n        except Exception:\n            logger.debug(\"Could not retrieve browser cookies\", exc_info=True)\n            return []\n        # Derive default domain from the browser's current page for host-only cookies\n        default_domain = \"\"\n        try:\n            current = self._driver.current_url\n            if current:\n                default_domain = urllib.parse.urlparse(current).hostname or \"\"\n        except Exception:\n            logger.debug(\"Could not get current URL for host-only cookie matching\", exc_info=True)\n        return [c for c in browser_cookies if _cookie_matches(c, url, default_domain)]","sourceCodeStart":586,"sourceCodeEnd":622,"githubUrl":"https://github.com/SeleniumHQ/selenium/blob/aa36b38e696a0909e973bdf5e2f9031ffe842c4b/py/selenium/webdriver/common/api_request_context.py#L586-L622","documentation":"`storage_state(path=...)` serializes the current browser cookies to JSON. If writing the file raises `OSError` (permission denied, read-only filesystem, missing directory, disk full), Selenium re-raises it as `OSError` with the path and underlying error. The state dict is still returned to the caller even if the write fails after the raise (the raise happens before the return).","triggerScenarios":"`api.storage_state(path=\"/readonly/state.json\")`, `api.storage_state(path=\"no/such/dir/state.json\")` (parent dir missing), or writing to a full disk. The path's parent directory must exist and be writable.","commonSituations":"CI artifact directory not created. Writing to a path inside a read-only container layer. Permissions on a shared volume. Disk/quota full.","solutions":["Create the parent directory first: `pathlib.Path(p).parent.mkdir(parents=True, exist_ok=True)`.","Write to a writable temp location: `tempfile.gettempdir()`.","Check write access: `os.access(pathlib.Path(p).parent, os.W_OK)`.","If you only need the dict, omit `path` and handle serialization yourself."],"exampleFix":"// before\nstate = api.storage_state(path=\"out/state.json\")  # OSError: dir missing\n// after\nimport pathlib\np = pathlib.Path(\"out/state.json\")\np.parent.mkdir(parents=True, exist_ok=True)\nstate = api.storage_state(path=str(p))","handlingStrategy":"validation","validationCode":"import pathlib, os\np = pathlib.Path(\"out/state.json\")\np.parent.mkdir(parents=True, exist_ok=True)\nassert os.access(p.parent, os.W_OK), f\"cannot write to {p.parent}\"\napi.storage_state(path=str(p))","typeGuard":"import os, pathlib\ndef storage_state_path_writable(path) -> bool:\n    parent = pathlib.Path(path).parent\n    return os.access(parent, os.W_OK)","tryCatchPattern":"try:\n    state = api.storage_state(path=path)\nexcept OSError:\n    state = api.storage_state()  # get dict without writing","preventionTips":["Create the parent directory before writing.","Use a writable temp dir if the target is read-only.","Omit path and serialize the dict yourself if filesystem is uncertain."],"tags":["storage-state","filesystem","write","api-request"],"backgroundTag":null,"analyzedSha":"aa36b38e696a0909e973bdf5e2f9031ffe842c4b","analyzedAt":"2026-08-14T02:32:32.244Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}