From 793a2ef426f85ce35cfb59ec7f5c2a09be5fdc13 Mon Sep 17 00:00:00 2001 From: Adam Dangoor Date: Thu, 20 Aug 2026 12:01:27 +0100 Subject: [PATCH 1/5] [py] Add WebDriver cookie type annotations Co-authored-by: Cursor --- .../webdriver/common/api_request_context.py | 20 ++++++------ py/selenium/webdriver/common/cookie.py | 31 +++++++++++++++++++ py/selenium/webdriver/remote/webdriver.py | 7 +++-- 3 files changed, 46 insertions(+), 12 deletions(-) create mode 100644 py/selenium/webdriver/common/cookie.py diff --git a/py/selenium/webdriver/common/api_request_context.py b/py/selenium/webdriver/common/api_request_context.py index 9c3a0129d16cf..bf23cd25a4671 100644 --- a/py/selenium/webdriver/common/api_request_context.py +++ b/py/selenium/webdriver/common/api_request_context.py @@ -29,6 +29,8 @@ import urllib3 from urllib3.util.retry import Retry +from selenium.webdriver.common.cookie import Cookie + if TYPE_CHECKING: from selenium.webdriver.remote.webdriver import WebDriver @@ -98,7 +100,7 @@ def dispose(self) -> None: self._body = b"" -def _cookie_matches(cookie: dict, url: str, default_domain: str = "") -> bool: +def _cookie_matches(cookie: Cookie, url: str, default_domain: str = "") -> bool: """Check if a browser cookie should be sent with a request to the given URL. Evaluates expiry, domain, path, and secure attribute matching per RFC 6265. @@ -151,7 +153,7 @@ def _cookie_matches(cookie: dict, url: str, default_domain: str = "") -> bool: return True -def _parse_set_cookie(header_value: str) -> dict: +def _parse_set_cookie(header_value: str) -> Cookie: """Parse a single Set-Cookie header value into a cookie dict. Uses manual parsing instead of http.cookies.SimpleCookie which is too @@ -171,7 +173,7 @@ def _parse_set_cookie(header_value: str) -> dict: name = name_value[:eq_idx].strip() value = name_value[eq_idx + 1 :].strip() - cookie: dict[str, Any] = {"name": name, "value": value} + cookie: Cookie = {"name": name, "value": value} has_max_age = False for part in parts[1:]: @@ -455,7 +457,7 @@ def _build_response(self, resp: urllib3.BaseHTTPResponse, url: str) -> APIRespon body=resp.data, ) - def _get_cookies_for_request(self, url: str) -> list[dict]: + def _get_cookies_for_request(self, url: str) -> list[Cookie]: """Get cookies that should be sent with the request. Overridden by subclasses.""" return [] @@ -558,7 +560,7 @@ def new_context( Returns: An _IsolatedAPIRequestContext instance. """ - cookies: list[dict] = [] + cookies: list[Cookie] = [] if storage_state is not None: if isinstance(storage_state, (str, pathlib.Path)): file_path = pathlib.Path(storage_state) @@ -604,7 +606,7 @@ def get_storage_state(self, path: str | pathlib.Path | None = None) -> dict[str, 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]: + def _get_cookies_for_request(self, url: str) -> list[Cookie]: """Get matching browser cookies for the request URL.""" try: browser_cookies = self._driver.get_cookies() @@ -657,7 +659,7 @@ def __init__( self, base_url: str = "", extra_headers: dict[str, str] | None = None, - cookies: list[dict] | None = None, + cookies: list[Cookie] | None = None, timeout: float = 30.0, max_redirects: int = 10, fail_on_status_code: bool = False, @@ -669,13 +671,13 @@ def __init__( max_redirects=max_redirects, fail_on_status_code=fail_on_status_code, ) - self._cookies: list[dict] = cookies or [] + self._cookies: list[Cookie] = cookies or [] def get_storage_state(self) -> dict[str, Any]: """Return the current cookies as a storage state dict.""" return {"cookies": list(self._cookies)} - def _get_cookies_for_request(self, url: str) -> list[dict]: + def _get_cookies_for_request(self, url: str) -> list[Cookie]: """Get matching cookies from the internal jar.""" # For isolated contexts, use the request hostname as default domain default_domain = urllib.parse.urlparse(url).hostname or "" diff --git a/py/selenium/webdriver/common/cookie.py b/py/selenium/webdriver/common/cookie.py new file mode 100644 index 0000000000000..7f6c6a040d6d0 --- /dev/null +++ b/py/selenium/webdriver/common/cookie.py @@ -0,0 +1,31 @@ +# Licensed to the Software Freedom Conservancy (SFC) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The SFC licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from typing_extensions import NotRequired, TypedDict + + +class Cookie(TypedDict, total=False): + """A WebDriver cookie dictionary.""" + + name: str + value: str + path: NotRequired[str] + domain: NotRequired[str] + secure: NotRequired[bool] + httpOnly: NotRequired[bool] + expiry: NotRequired[int] + sameSite: NotRequired[str] diff --git a/py/selenium/webdriver/remote/webdriver.py b/py/selenium/webdriver/remote/webdriver.py index a99369ffa1112..45429735bc267 100644 --- a/py/selenium/webdriver/remote/webdriver.py +++ b/py/selenium/webdriver/remote/webdriver.py @@ -57,6 +57,7 @@ from selenium.webdriver.common.bidi.storage import Storage from selenium.webdriver.common.bidi.webextension import WebExtension from selenium.webdriver.common.by import By +from selenium.webdriver.common.cookie import Cookie from selenium.webdriver.common.options import ArgOptions, BaseOptions from selenium.webdriver.remote.bidi_connection import BidiConnection from selenium.webdriver.remote.client_config import ClientConfig @@ -729,7 +730,7 @@ def refresh(self) -> None: """Refreshes the current page.""" self.execute(Command.REFRESH) - def get_cookies(self) -> list[dict]: + def get_cookies(self) -> list[Cookie]: """Get all cookies visible to the current WebDriver instance. Returns: @@ -738,7 +739,7 @@ def get_cookies(self) -> list[dict]: """ return self.execute(Command.GET_ALL_COOKIES)["value"] - def get_cookie(self, name) -> dict | None: + def get_cookie(self, name: str) -> Cookie | None: """Get a single cookie by name (case-sensitive,). Returns: @@ -777,7 +778,7 @@ def delete_all_cookies(self) -> None: """Delete all cookies in the scope of the session.""" self.execute(Command.DELETE_ALL_COOKIES) - def add_cookie(self, cookie_dict) -> None: + def add_cookie(self, cookie_dict: Cookie) -> None: """Adds a cookie to your current session. Args: From c3365b95383b695b3423bda5536bd4522643a98e Mon Sep 17 00:00:00 2001 From: Adam Dangoor Date: Wed, 9 Sep 2026 11:26:29 +0100 Subject: [PATCH 2/5] [py] Address cookie typing review feedback --- .../webdriver/common/api_request_context.py | 15 ++++++++------- py/selenium/webdriver/common/cookie.py | 2 +- py/selenium/webdriver/remote/webdriver.py | 7 +++---- .../webdriver/common/api_request_context_tests.py | 4 ++-- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/py/selenium/webdriver/common/api_request_context.py b/py/selenium/webdriver/common/api_request_context.py index bf23cd25a4671..160a2b8108cd8 100644 --- a/py/selenium/webdriver/common/api_request_context.py +++ b/py/selenium/webdriver/common/api_request_context.py @@ -24,7 +24,7 @@ import urllib.parse from email.utils import parsedate_to_datetime from http.client import responses as http_status_phrases -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast import urllib3 from urllib3.util.retry import Retry @@ -153,7 +153,7 @@ def _cookie_matches(cookie: Cookie, url: str, default_domain: str = "") -> bool: return True -def _parse_set_cookie(header_value: str) -> Cookie: +def _parse_set_cookie(header_value: str) -> Cookie | None: """Parse a single Set-Cookie header value into a cookie dict. Uses manual parsing instead of http.cookies.SimpleCookie which is too @@ -163,13 +163,14 @@ def _parse_set_cookie(header_value: str) -> Cookie: header_value: The Set-Cookie header string. Returns: - A dict with cookie attributes suitable for driver.add_cookie(). + A dict with cookie attributes suitable for driver.add_cookie(), or None + if the header does not contain a name-value pair. """ parts = header_value.split(";") name_value = parts[0].strip() eq_idx = name_value.find("=") if eq_idx == -1: - return {} + return None name = name_value[:eq_idx].strip() value = name_value[eq_idx + 1 :].strip() @@ -609,7 +610,7 @@ def get_storage_state(self, path: str | pathlib.Path | None = None) -> dict[str, def _get_cookies_for_request(self, url: str) -> list[Cookie]: """Get matching browser cookies for the request URL.""" try: - browser_cookies = self._driver.get_cookies() + browser_cookies = cast(list[Cookie], self._driver.get_cookies()) except Exception: logger.debug("Could not retrieve browser cookies", exc_info=True) return [] @@ -628,7 +629,7 @@ def _handle_response_cookies(self, set_cookie_headers: list[str], url: str) -> N parsed_url = urllib.parse.urlparse(url) for sc_header in set_cookie_headers: cookie = _parse_set_cookie(sc_header) - if not cookie.get("name"): + if cookie is None or not cookie["name"]: continue cookie.setdefault("domain", parsed_url.hostname or "") cookie.setdefault("path", "/") @@ -689,7 +690,7 @@ def _handle_response_cookies(self, set_cookie_headers: list[str], url: str) -> N now = int(time.time()) for sc_header in set_cookie_headers: cookie = _parse_set_cookie(sc_header) - if not cookie.get("name"): + if cookie is None or not cookie["name"]: continue cookie.setdefault("domain", parsed_url.hostname or "") cookie.setdefault("path", "/") diff --git a/py/selenium/webdriver/common/cookie.py b/py/selenium/webdriver/common/cookie.py index 7f6c6a040d6d0..d9afa2e29f201 100644 --- a/py/selenium/webdriver/common/cookie.py +++ b/py/selenium/webdriver/common/cookie.py @@ -18,7 +18,7 @@ from typing_extensions import NotRequired, TypedDict -class Cookie(TypedDict, total=False): +class Cookie(TypedDict): """A WebDriver cookie dictionary.""" name: str diff --git a/py/selenium/webdriver/remote/webdriver.py b/py/selenium/webdriver/remote/webdriver.py index 45429735bc267..a99369ffa1112 100644 --- a/py/selenium/webdriver/remote/webdriver.py +++ b/py/selenium/webdriver/remote/webdriver.py @@ -57,7 +57,6 @@ from selenium.webdriver.common.bidi.storage import Storage from selenium.webdriver.common.bidi.webextension import WebExtension from selenium.webdriver.common.by import By -from selenium.webdriver.common.cookie import Cookie from selenium.webdriver.common.options import ArgOptions, BaseOptions from selenium.webdriver.remote.bidi_connection import BidiConnection from selenium.webdriver.remote.client_config import ClientConfig @@ -730,7 +729,7 @@ def refresh(self) -> None: """Refreshes the current page.""" self.execute(Command.REFRESH) - def get_cookies(self) -> list[Cookie]: + def get_cookies(self) -> list[dict]: """Get all cookies visible to the current WebDriver instance. Returns: @@ -739,7 +738,7 @@ def get_cookies(self) -> list[Cookie]: """ return self.execute(Command.GET_ALL_COOKIES)["value"] - def get_cookie(self, name: str) -> Cookie | None: + def get_cookie(self, name) -> dict | None: """Get a single cookie by name (case-sensitive,). Returns: @@ -778,7 +777,7 @@ def delete_all_cookies(self) -> None: """Delete all cookies in the scope of the session.""" self.execute(Command.DELETE_ALL_COOKIES) - def add_cookie(self, cookie_dict: Cookie) -> None: + def add_cookie(self, cookie_dict) -> None: """Adds a cookie to your current session. Args: diff --git a/py/test/unit/selenium/webdriver/common/api_request_context_tests.py b/py/test/unit/selenium/webdriver/common/api_request_context_tests.py index e1db2a4f19227..f0bddcf3d50e4 100644 --- a/py/test/unit/selenium/webdriver/common/api_request_context_tests.py +++ b/py/test/unit/selenium/webdriver/common/api_request_context_tests.py @@ -439,9 +439,9 @@ def test_invalid_max_age_ignored(): assert "expiry" not in c -def test_no_equals_returns_empty(): +def test_no_equals_returns_none(): c = _parse_set_cookie("malformed") - assert c == {} + assert c is None def test_value_with_equals_sign(): From dcbda9dcc2c6f561932dbb02d7947d8c72055928 Mon Sep 17 00:00:00 2001 From: Adam Dangoor Date: Sat, 12 Sep 2026 14:58:34 +0100 Subject: [PATCH 3/5] Complete get_cookies return type --- py/selenium/webdriver/remote/webdriver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/py/selenium/webdriver/remote/webdriver.py b/py/selenium/webdriver/remote/webdriver.py index a99369ffa1112..209538cabbda3 100644 --- a/py/selenium/webdriver/remote/webdriver.py +++ b/py/selenium/webdriver/remote/webdriver.py @@ -729,7 +729,7 @@ def refresh(self) -> None: """Refreshes the current page.""" self.execute(Command.REFRESH) - def get_cookies(self) -> list[dict]: + def get_cookies(self) -> list[dict[str, object]]: """Get all cookies visible to the current WebDriver instance. Returns: From 130504a640f41fd548c9732a7302ddbb12a4978f Mon Sep 17 00:00:00 2001 From: Diego Molina Date: Thu, 29 Oct 2026 22:06:38 +0100 Subject: [PATCH 4/5] [py] Use Any for get_cookies dict values Keeps cookie values typed as Any so existing typed callers do not need changes. Co-Authored-By: Claude Opus 5.5 --- py/selenium/webdriver/remote/webdriver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/py/selenium/webdriver/remote/webdriver.py b/py/selenium/webdriver/remote/webdriver.py index 4fa2ad7fdf67e..0cafe5ba5be91 100644 --- a/py/selenium/webdriver/remote/webdriver.py +++ b/py/selenium/webdriver/remote/webdriver.py @@ -793,7 +793,7 @@ def refresh(self) -> None: """Refreshes the current page.""" self.execute(Command.REFRESH) - def get_cookies(self) -> list[dict[str, object]]: + def get_cookies(self) -> list[dict[str, Any]]: """Get all cookies visible to the current WebDriver instance. Returns: From e5a9efdfe1873b737af8392d7e4a48e6c6fa2096 Mon Sep 17 00:00:00 2001 From: Diego Molina Date: Thu, 29 Oct 2026 23:01:14 +0100 Subject: [PATCH 5/5] [py] Add cookie module to the api_request_context Bazel target Co-Authored-By: Claude Opus 5.5 --- py/BUILD.bazel | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/py/BUILD.bazel b/py/BUILD.bazel index 2cf79322fdba4..d022c8491d3ff 100644 --- a/py/BUILD.bazel +++ b/py/BUILD.bazel @@ -376,6 +376,7 @@ py_library( "selenium/webdriver/common/actions/**", "selenium/webdriver/common/alert.py", "selenium/webdriver/common/api_request_context.py", + "selenium/webdriver/common/cookie.py", "selenium/webdriver/common/_bidi/**", "selenium/webdriver/common/bidi/**", "selenium/webdriver/common/devtools/**", @@ -436,10 +437,16 @@ py_library( py_library( name = "common_api_request_context", - srcs = ["selenium/webdriver/common/api_request_context.py"], + srcs = [ + "selenium/webdriver/common/api_request_context.py", + "selenium/webdriver/common/cookie.py", + ], imports = ["."], visibility = ["//visibility:public"], - deps = [":exceptions"], + deps = [ + ":exceptions", + requirement("typing_extensions"), + ], ) py_library(