SeleniumHQ/selenium · error · OSError
Cannot write storage state to
Error message
Cannot write storage state to {file_path}: {e} What it means
`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).
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.
Example fix
// before
state = api.storage_state(path="out/state.json") # OSError: dir missing
// after
import pathlib
p = pathlib.Path("out/state.json")
p.parent.mkdir(parents=True, exist_ok=True)
state = api.storage_state(path=str(p)) Defensive patterns
Strategy: validation
Validate before calling
import pathlib, os
p = pathlib.Path("out/state.json")
p.parent.mkdir(parents=True, exist_ok=True)
assert os.access(p.parent, os.W_OK), f"cannot write to {p.parent}"
api.storage_state(path=str(p)) Type guard
import os, pathlib
def storage_state_path_writable(path) -> bool:
parent = pathlib.Path(path).parent
return os.access(parent, os.W_OK) Try / catch
try:
state = api.storage_state(path=path)
except OSError:
state = api.storage_state() # get dict without writing Prevention
- 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.
When it happens
Trigger: `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.
Common situations: CI artifact directory not created. Writing to a path inside a read-only container layer. Permissions on a shared volume. Disk/quota full.
Related errors
- Cannot read storage state file
- Storage state file not found
- Invalid JSON in storage state file
- Add-on path does not exist
- Can't find server .jar located at
AI-assisted analysis of SeleniumHQ/selenium@aa36b38e69 (2026-08-14).
Data as JSON: /api/errors/a78beb97d3f55a9b.
Report an issue: GitHub.
Appendix: source
Thrown at py/selenium/webdriver/common/api_request_context.py:604
def get_storage_state(self, path: str | pathlib.Path | None = None) -> dict[str, Any]:
"""Export the current browser cookies as a storage state dict.
Args:
path: Optional file path to save the storage state as JSON.
Returns:
A dict with a "cookies" key containing the browser cookies.
"""
cookies = self._driver.get_cookies()
state: dict[str, Any] = {"cookies": cookies}
if path is not None:
file_path = pathlib.Path(path)
try:
with open(file_path, "w") as f:
json.dump(state, f, indent=2)
except OSError as e:
raise OSError(f"Cannot write storage state to {file_path}: {e}") from e
return state
def _get_cookies_for_request(self, url: str) -> list[dict]:
"""Get matching browser cookies for the request URL."""
try:
browser_cookies = self._driver.get_cookies()
except Exception:
logger.debug("Could not retrieve browser cookies", exc_info=True)
return []
# Derive default domain from the browser's current page for host-only cookies
default_domain = ""
try:
current = self._driver.current_url
if current:
default_domain = urllib.parse.urlparse(current).hostname or ""
except Exception:
logger.debug("Could not get current URL for host-only cookie matching", exc_info=True)
return [c for c in browser_cookies if _cookie_matches(c, url, default_domain)]View on GitHub (pinned to aa36b38e69)