selenium-netwire 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- netwire/__init__.py +17 -0
- netwire/_backend.py +459 -0
- netwire/_cdp.py +133 -0
- netwire/_config.py +115 -0
- netwire/_har.py +92 -0
- netwire/_mixin.py +134 -0
- netwire/_relay.py +258 -0
- netwire/request.py +229 -0
- netwire/utils.py +39 -0
- netwire/webdriver.py +70 -0
- selenium_netwire-0.1.0.dist-info/METADATA +194 -0
- selenium_netwire-0.1.0.dist-info/RECORD +14 -0
- selenium_netwire-0.1.0.dist-info/WHEEL +4 -0
- selenium_netwire-0.1.0.dist-info/licenses/LICENSE +21 -0
netwire/request.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Request, Response and header objects, compatible with selenium-wire's."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from typing import Iterable, Iterator
|
|
7
|
+
from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class HTTPHeaders:
|
|
11
|
+
"""Case-insensitive headers that keep duplicates, like selenium-wire's.
|
|
12
|
+
|
|
13
|
+
Assigning a header adds it, even if one with that name exists already, so
|
|
14
|
+
to replace a header delete it first::
|
|
15
|
+
|
|
16
|
+
del request.headers["Referer"]
|
|
17
|
+
request.headers["Referer"] = "https://example.com/"
|
|
18
|
+
|
|
19
|
+
Reading a missing header returns ``None``.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, items: Iterable[tuple[str, str]] = ()) -> None:
|
|
23
|
+
self._items: list[tuple[str, str]] = [(str(k), str(v)) for k, v in items]
|
|
24
|
+
|
|
25
|
+
def __getitem__(self, name: str) -> str | None:
|
|
26
|
+
return self.get(name)
|
|
27
|
+
|
|
28
|
+
def __setitem__(self, name: str, value: str) -> None:
|
|
29
|
+
self._items.append((str(name), str(value)))
|
|
30
|
+
|
|
31
|
+
def __delitem__(self, name: str) -> None:
|
|
32
|
+
lowered = name.lower()
|
|
33
|
+
self._items = [(k, v) for k, v in self._items if k.lower() != lowered]
|
|
34
|
+
|
|
35
|
+
def __contains__(self, name: object) -> bool:
|
|
36
|
+
return isinstance(name, str) and any(k.lower() == name.lower() for k, _ in self._items)
|
|
37
|
+
|
|
38
|
+
def __iter__(self) -> Iterator[str]:
|
|
39
|
+
return iter(self.keys())
|
|
40
|
+
|
|
41
|
+
def __len__(self) -> int:
|
|
42
|
+
return len(self._items)
|
|
43
|
+
|
|
44
|
+
def __eq__(self, other: object) -> bool:
|
|
45
|
+
if isinstance(other, HTTPHeaders):
|
|
46
|
+
return self._items == other._items
|
|
47
|
+
if isinstance(other, dict):
|
|
48
|
+
return dict(self.items()) == other
|
|
49
|
+
return NotImplemented
|
|
50
|
+
|
|
51
|
+
def get(self, name: str, default: str | None = None) -> str | None:
|
|
52
|
+
lowered = name.lower()
|
|
53
|
+
for k, v in self._items:
|
|
54
|
+
if k.lower() == lowered:
|
|
55
|
+
return v
|
|
56
|
+
return default
|
|
57
|
+
|
|
58
|
+
def get_all(self, name: str, default: list[str] | None = None) -> list[str] | None:
|
|
59
|
+
lowered = name.lower()
|
|
60
|
+
values = [v for k, v in self._items if k.lower() == lowered]
|
|
61
|
+
return values or default
|
|
62
|
+
|
|
63
|
+
def replace_header(self, name: str, value: str) -> None:
|
|
64
|
+
"""Replace the first header called ``name``; raises KeyError if there is none."""
|
|
65
|
+
lowered = name.lower()
|
|
66
|
+
for i, (k, _) in enumerate(self._items):
|
|
67
|
+
if k.lower() == lowered:
|
|
68
|
+
self._items[i] = (k, str(value))
|
|
69
|
+
return
|
|
70
|
+
raise KeyError(name)
|
|
71
|
+
|
|
72
|
+
def keys(self) -> list[str]:
|
|
73
|
+
return [k for k, _ in self._items]
|
|
74
|
+
|
|
75
|
+
def values(self) -> list[str]:
|
|
76
|
+
return [v for _, v in self._items]
|
|
77
|
+
|
|
78
|
+
def items(self) -> list[tuple[str, str]]:
|
|
79
|
+
return list(self._items)
|
|
80
|
+
|
|
81
|
+
def copy(self) -> "HTTPHeaders":
|
|
82
|
+
return HTTPHeaders(self._items)
|
|
83
|
+
|
|
84
|
+
def __repr__(self) -> str:
|
|
85
|
+
return f"HTTPHeaders({self._items!r})"
|
|
86
|
+
|
|
87
|
+
def __str__(self) -> str:
|
|
88
|
+
return "".join(f"{k}: {v}\n" for k, v in self._items)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class WebSocketMessage:
|
|
92
|
+
"""One websocket frame sent or received on a websocket request."""
|
|
93
|
+
|
|
94
|
+
def __init__(self, from_client: bool, content: str | bytes, date: datetime) -> None:
|
|
95
|
+
self.from_client = from_client
|
|
96
|
+
self.content = content
|
|
97
|
+
self.date = date
|
|
98
|
+
|
|
99
|
+
def __repr__(self) -> str:
|
|
100
|
+
direction = "sent" if self.from_client else "received"
|
|
101
|
+
return f"WebSocketMessage({direction}, {self.content!r:.60})"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class Response:
|
|
105
|
+
"""An HTTP response. ``body`` is already decompressed."""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
*,
|
|
110
|
+
status_code: int,
|
|
111
|
+
reason: str = "",
|
|
112
|
+
headers: Iterable[tuple[str, str]] = (),
|
|
113
|
+
body: bytes = b"",
|
|
114
|
+
date: datetime | None = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
self.status_code = status_code
|
|
117
|
+
self.reason = reason
|
|
118
|
+
self.headers = HTTPHeaders(headers)
|
|
119
|
+
self.body = body
|
|
120
|
+
self.date = date or datetime.now()
|
|
121
|
+
|
|
122
|
+
def __repr__(self) -> str:
|
|
123
|
+
return f"Response(status_code={self.status_code!r}, reason={self.reason!r})"
|
|
124
|
+
|
|
125
|
+
def __str__(self) -> str:
|
|
126
|
+
return f"{self.status_code} {self.reason}".strip()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Request:
|
|
130
|
+
"""An HTTP request made by the browser, and its response once it has one."""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
*,
|
|
135
|
+
method: str,
|
|
136
|
+
url: str,
|
|
137
|
+
headers: Iterable[tuple[str, str]] = (),
|
|
138
|
+
body: bytes = b"",
|
|
139
|
+
date: datetime | None = None,
|
|
140
|
+
id: str | None = None,
|
|
141
|
+
) -> None:
|
|
142
|
+
self.id = id
|
|
143
|
+
self.method = method
|
|
144
|
+
self.url = url
|
|
145
|
+
self.headers = HTTPHeaders(headers)
|
|
146
|
+
self.body = body
|
|
147
|
+
self.date = date or datetime.now()
|
|
148
|
+
self.response: Response | None = None
|
|
149
|
+
self.ws_messages: list[WebSocketMessage] = []
|
|
150
|
+
self.cert: dict = {}
|
|
151
|
+
self.error: str | None = None
|
|
152
|
+
self._body_loaded = False
|
|
153
|
+
# Set by abort() and create_response() inside a request interceptor.
|
|
154
|
+
self._abort_code: int | None = None
|
|
155
|
+
self._mock: Response | None = None
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def host(self) -> str:
|
|
159
|
+
return urlsplit(self.url).netloc
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def path(self) -> str:
|
|
163
|
+
return urlsplit(self.url).path
|
|
164
|
+
|
|
165
|
+
@path.setter
|
|
166
|
+
def path(self, path: str) -> None:
|
|
167
|
+
parts = urlsplit(self.url)
|
|
168
|
+
self.url = urlunsplit((parts.scheme, parts.netloc, path, parts.query, parts.fragment))
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def querystring(self) -> str:
|
|
172
|
+
return urlsplit(self.url).query
|
|
173
|
+
|
|
174
|
+
@querystring.setter
|
|
175
|
+
def querystring(self, query: str) -> None:
|
|
176
|
+
parts = urlsplit(self.url)
|
|
177
|
+
self.url = urlunsplit((parts.scheme, parts.netloc, parts.path, query, parts.fragment))
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def params(self) -> dict[str, str | list[str]]:
|
|
181
|
+
"""Query string parameters, or form fields for a form-encoded body.
|
|
182
|
+
|
|
183
|
+
A name that appears more than once maps to a list of its values.
|
|
184
|
+
"""
|
|
185
|
+
content_type = (self.headers.get("Content-Type") or "").split(";")[0].strip()
|
|
186
|
+
if content_type == "application/x-www-form-urlencoded" and self.method in ("POST", "PUT", "PATCH"):
|
|
187
|
+
source = self.body.decode("utf-8", "replace")
|
|
188
|
+
else:
|
|
189
|
+
source = self.querystring
|
|
190
|
+
parsed = parse_qs(source, keep_blank_values=True)
|
|
191
|
+
return {k: v[0] if len(v) == 1 else v for k, v in parsed.items()}
|
|
192
|
+
|
|
193
|
+
@params.setter
|
|
194
|
+
def params(self, params: dict) -> None:
|
|
195
|
+
encoded = urlencode(params, doseq=True)
|
|
196
|
+
content_type = (self.headers.get("Content-Type") or "").split(";")[0].strip()
|
|
197
|
+
if content_type == "application/x-www-form-urlencoded" and self.method in ("POST", "PUT", "PATCH"):
|
|
198
|
+
self.body = encoded.encode()
|
|
199
|
+
else:
|
|
200
|
+
self.querystring = encoded
|
|
201
|
+
|
|
202
|
+
def abort(self, error_code: int = 403) -> None:
|
|
203
|
+
"""Answer the request at once with ``error_code``; nothing is sent to the server.
|
|
204
|
+
|
|
205
|
+
For use inside a request interceptor.
|
|
206
|
+
"""
|
|
207
|
+
self._abort_code = error_code
|
|
208
|
+
|
|
209
|
+
def create_response(
|
|
210
|
+
self,
|
|
211
|
+
status_code: int,
|
|
212
|
+
headers: Iterable[tuple[str, str]] | dict = (),
|
|
213
|
+
body: bytes | str = b"",
|
|
214
|
+
) -> None:
|
|
215
|
+
"""Answer the request with this response; nothing is sent to the server.
|
|
216
|
+
|
|
217
|
+
For use inside a request interceptor.
|
|
218
|
+
"""
|
|
219
|
+
if isinstance(headers, dict):
|
|
220
|
+
headers = headers.items()
|
|
221
|
+
if isinstance(body, str):
|
|
222
|
+
body = body.encode()
|
|
223
|
+
self._mock = Response(status_code=status_code, headers=headers, body=body)
|
|
224
|
+
|
|
225
|
+
def __repr__(self) -> str:
|
|
226
|
+
return f"Request(method={self.method!r}, url={self.url!r})"
|
|
227
|
+
|
|
228
|
+
def __str__(self) -> str:
|
|
229
|
+
return self.url
|
netwire/utils.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Helpers kept for code written against ``seleniumwire.utils``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import gzip
|
|
6
|
+
import zlib
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def decode(data: bytes, encoding: str | None) -> bytes:
|
|
10
|
+
"""Decompress ``data`` sent with the given Content-Encoding.
|
|
11
|
+
|
|
12
|
+
netwire hands out bodies already decompressed, so code that still calls
|
|
13
|
+
``decode(response.body, response.headers.get('Content-Encoding'))`` gets
|
|
14
|
+
the body back unchanged when it is not compressed.
|
|
15
|
+
"""
|
|
16
|
+
encoding = (encoding or "identity").lower().strip()
|
|
17
|
+
try:
|
|
18
|
+
if encoding in ("gzip", "x-gzip"):
|
|
19
|
+
return gzip.decompress(data)
|
|
20
|
+
if encoding == "deflate":
|
|
21
|
+
try:
|
|
22
|
+
return zlib.decompress(data)
|
|
23
|
+
except zlib.error:
|
|
24
|
+
return zlib.decompress(data, -zlib.MAX_WBITS)
|
|
25
|
+
if encoding == "br":
|
|
26
|
+
try:
|
|
27
|
+
import brotli # type: ignore
|
|
28
|
+
except ImportError:
|
|
29
|
+
return data
|
|
30
|
+
return brotli.decompress(data)
|
|
31
|
+
if encoding == "zstd":
|
|
32
|
+
try:
|
|
33
|
+
import zstandard # type: ignore
|
|
34
|
+
except ImportError:
|
|
35
|
+
return data
|
|
36
|
+
return zstandard.ZstdDecompressor().decompress(data)
|
|
37
|
+
except Exception:
|
|
38
|
+
return data
|
|
39
|
+
return data
|
netwire/webdriver.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Drop-in replacement for ``seleniumwire.webdriver``.
|
|
2
|
+
|
|
3
|
+
from netwire import webdriver
|
|
4
|
+
|
|
5
|
+
driver = webdriver.Chrome(seleniumwire_options={...})
|
|
6
|
+
|
|
7
|
+
Everything else in ``selenium.webdriver`` is re-exported unchanged.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from selenium.webdriver import * # noqa: F401,F403
|
|
13
|
+
from selenium.webdriver import Chrome as _Chrome
|
|
14
|
+
from selenium.webdriver import ChromeOptions
|
|
15
|
+
from selenium.webdriver import Edge as _Edge
|
|
16
|
+
from selenium.webdriver import EdgeOptions
|
|
17
|
+
|
|
18
|
+
from ._backend import Backend
|
|
19
|
+
from ._config import Config
|
|
20
|
+
from ._mixin import InspectRequestsMixin
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _prepare(kwargs: dict, options_class, seleniumwire_options, netwire_options) -> Config:
|
|
24
|
+
config = Config({**(seleniumwire_options or {}), **(netwire_options or {})})
|
|
25
|
+
config.start_relay()
|
|
26
|
+
options = kwargs.get("options")
|
|
27
|
+
if options is None:
|
|
28
|
+
options = kwargs["options"] = options_class()
|
|
29
|
+
for argument in config.browser_arguments():
|
|
30
|
+
if argument not in options.arguments:
|
|
31
|
+
options.add_argument(argument)
|
|
32
|
+
return config
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Chrome(InspectRequestsMixin, _Chrome):
|
|
36
|
+
"""``selenium.webdriver.Chrome`` that captures and can modify network traffic."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, *args, seleniumwire_options: dict | None = None, netwire_options: dict | None = None, **kwargs):
|
|
39
|
+
if args:
|
|
40
|
+
kwargs.setdefault("options", args[0])
|
|
41
|
+
args = args[1:]
|
|
42
|
+
config = _prepare(kwargs, ChromeOptions, seleniumwire_options, netwire_options)
|
|
43
|
+
super().__init__(*args, **kwargs)
|
|
44
|
+
try:
|
|
45
|
+
address = self.capabilities["goog:chromeOptions"]["debuggerAddress"]
|
|
46
|
+
self._netwire = Backend(address, config)
|
|
47
|
+
except Exception:
|
|
48
|
+
if config.relay is not None:
|
|
49
|
+
config.relay.close()
|
|
50
|
+
super().quit()
|
|
51
|
+
raise
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Edge(InspectRequestsMixin, _Edge):
|
|
55
|
+
"""``selenium.webdriver.Edge`` that captures and can modify network traffic."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, *args, seleniumwire_options: dict | None = None, netwire_options: dict | None = None, **kwargs):
|
|
58
|
+
if args:
|
|
59
|
+
kwargs.setdefault("options", args[0])
|
|
60
|
+
args = args[1:]
|
|
61
|
+
config = _prepare(kwargs, EdgeOptions, seleniumwire_options, netwire_options)
|
|
62
|
+
super().__init__(*args, **kwargs)
|
|
63
|
+
try:
|
|
64
|
+
address = self.capabilities["ms:edgeOptions"]["debuggerAddress"]
|
|
65
|
+
self._netwire = Backend(address, config)
|
|
66
|
+
except Exception:
|
|
67
|
+
if config.relay is not None:
|
|
68
|
+
config.relay.close()
|
|
69
|
+
super().quit()
|
|
70
|
+
raise
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: selenium-netwire
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Capture and modify the browser's network traffic in Selenium. A maintained, drop-in successor to selenium-wire, built on the browser's DevTools protocol instead of a proxy.
|
|
5
|
+
Project-URL: Homepage, https://github.com/tugayabdulla/selenium-netwire
|
|
6
|
+
Project-URL: Issues, https://github.com/tugayabdulla/selenium-netwire/issues
|
|
7
|
+
Author: Tugay Abdullazade
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: cdp,devtools,intercept,network,proxy,scraping,selenium,selenium-wire
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Framework :: Pytest
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
|
|
16
|
+
Classifier: Topic :: Software Development :: Testing
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Requires-Dist: selenium>=4.20
|
|
19
|
+
Requires-Dist: websocket-client>=1.6
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# selenium-netwire
|
|
23
|
+
|
|
24
|
+
See and change the network traffic of a Selenium browser: requests, responses,
|
|
25
|
+
bodies, websocket messages, and proxies with a username and password.
|
|
26
|
+
|
|
27
|
+
It is a drop-in replacement for [selenium-wire](https://github.com/wkeeling/selenium-wire),
|
|
28
|
+
which was archived in January 2024. Same API, but built on the browser's
|
|
29
|
+
DevTools protocol instead of a man-in-the-middle proxy, so there are no
|
|
30
|
+
certificates to install and nothing sits between the browser and the site.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install selenium-netwire
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from netwire import webdriver
|
|
38
|
+
|
|
39
|
+
driver = webdriver.Chrome()
|
|
40
|
+
driver.get("https://example.com")
|
|
41
|
+
|
|
42
|
+
for request in driver.requests:
|
|
43
|
+
if request.response:
|
|
44
|
+
print(request.method, request.url, request.response.status_code)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Moving from selenium-wire
|
|
48
|
+
|
|
49
|
+
Change the import. Everything else stays the same, `seleniumwire_options`
|
|
50
|
+
included:
|
|
51
|
+
|
|
52
|
+
```diff
|
|
53
|
+
- from seleniumwire import webdriver
|
|
54
|
+
+ from netwire import webdriver
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Options that only configured selenium-wire's own proxy (`ca_cert`, `ca_key`,
|
|
58
|
+
`verify_ssl`, `port`, `addr`, `request_storage`, `disable_encoding` and so on)
|
|
59
|
+
are accepted and ignored.
|
|
60
|
+
|
|
61
|
+
## Why not selenium-wire
|
|
62
|
+
|
|
63
|
+
selenium-wire sends all browser traffic through a proxy it runs inside your
|
|
64
|
+
Python process, and decrypts HTTPS with its own certificate. That is why it
|
|
65
|
+
needed certificates, broke when its dependencies moved on (`blinker._saferef`),
|
|
66
|
+
slowed pages down, and changed the browser's TLS fingerprint, which anti-bot
|
|
67
|
+
systems notice.
|
|
68
|
+
|
|
69
|
+
netwire asks the browser itself. Chrome reports every request over its
|
|
70
|
+
DevTools protocol and can pause, change or answer requests there. The traffic
|
|
71
|
+
goes from the browser to the site exactly as it would without netwire.
|
|
72
|
+
|
|
73
|
+
## Why not Selenium's own network API
|
|
74
|
+
|
|
75
|
+
Selenium 4 has `driver.network` over WebDriver BiDi. Capturing works, but
|
|
76
|
+
changing requests does not mix with normal Selenium code yet: with a request
|
|
77
|
+
handler set, `driver.get()` hangs in Chrome, because ChromeDriver does not
|
|
78
|
+
process the "continue this request" command while `get()` is running
|
|
79
|
+
([selenium#17373](https://github.com/SeleniumHQ/selenium/issues/17373),
|
|
80
|
+
[selenium#18116](https://github.com/SeleniumHQ/selenium/issues/18116)).
|
|
81
|
+
netwire talks to the browser's DevTools socket directly, next to
|
|
82
|
+
ChromeDriver, so `get()`, clicks and everything else keep working while
|
|
83
|
+
requests are being changed.
|
|
84
|
+
|
|
85
|
+
## Capturing
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
driver.requests # every captured request, oldest first
|
|
89
|
+
driver.last_request
|
|
90
|
+
driver.iter_requests()
|
|
91
|
+
del driver.requests # clear
|
|
92
|
+
|
|
93
|
+
request = driver.wait_for_request("/api/products", timeout=10)
|
|
94
|
+
request.url, request.method, request.headers, request.body, request.params
|
|
95
|
+
request.response.status_code, request.response.headers, request.response.body
|
|
96
|
+
request.ws_messages # websocket frames, for websocket requests
|
|
97
|
+
request.cert # the server's TLS certificate details
|
|
98
|
+
|
|
99
|
+
driver.scopes = [".*example.com/api/.*"] # only capture these
|
|
100
|
+
driver.har # HAR 1.2 archive as JSON
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Response bodies are already decompressed. `netwire.utils.decode()` is there
|
|
104
|
+
for code written for selenium-wire and returns the body unchanged.
|
|
105
|
+
|
|
106
|
+
## Changing requests and responses
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
def interceptor(request):
|
|
110
|
+
del request.headers["User-Agent"]
|
|
111
|
+
request.headers["User-Agent"] = "my-agent"
|
|
112
|
+
if request.path.endswith((".png", ".jpg")):
|
|
113
|
+
request.abort()
|
|
114
|
+
if request.url == "https://example.com/api/config":
|
|
115
|
+
request.create_response(200, {"Content-Type": "application/json"}, b'{"beta": true}')
|
|
116
|
+
|
|
117
|
+
driver.request_interceptor = interceptor
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def response_interceptor(request, response):
|
|
121
|
+
if request.path == "/api/data":
|
|
122
|
+
response.body = b'{"value": 7}'
|
|
123
|
+
|
|
124
|
+
driver.response_interceptor = response_interceptor
|
|
125
|
+
|
|
126
|
+
del driver.request_interceptor # stop intercepting
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Headers behave like selenium-wire's: names are case-insensitive, setting a
|
|
130
|
+
header adds it, so delete it first to replace it, and a missing header reads
|
|
131
|
+
as `None`.
|
|
132
|
+
|
|
133
|
+
## Proxies
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
driver = webdriver.Chrome(seleniumwire_options={
|
|
137
|
+
"proxy": {
|
|
138
|
+
"https": "http://user:pass@proxy.example.com:8080",
|
|
139
|
+
"no_proxy": "localhost,127.0.0.1",
|
|
140
|
+
}
|
|
141
|
+
})
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
| Proxy | How |
|
|
145
|
+
| --- | --- |
|
|
146
|
+
| HTTP or HTTPS, with or without user:pass | Chrome connects to it; netwire answers its login |
|
|
147
|
+
| SOCKS5 without a login | Chrome connects to it |
|
|
148
|
+
| SOCKS5 with user:pass | through netwire's relay (below) |
|
|
149
|
+
| `custom_authorization`, e.g. a Bearer token | through the relay |
|
|
150
|
+
| `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` | read when no `proxy` option is given |
|
|
151
|
+
|
|
152
|
+
Chrome cannot log in to SOCKS proxies or change its proxy after starting. For
|
|
153
|
+
those, netwire starts a small relay on 127.0.0.1: Chrome uses it as a plain
|
|
154
|
+
SOCKS5 proxy and the relay connects through the real one. It only forwards
|
|
155
|
+
bytes; it does not decrypt anything.
|
|
156
|
+
|
|
157
|
+
To switch proxies while the driver runs, start with the relay on:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
driver = webdriver.Chrome(netwire_options={"relay": True})
|
|
161
|
+
driver.proxy = {"https": "socks5://user:pass@proxy-1.example.com:1080"}
|
|
162
|
+
driver.get(...)
|
|
163
|
+
driver.proxy = {"https": "http://user:pass@proxy-2.example.com:8080"}
|
|
164
|
+
driver.get(...)
|
|
165
|
+
del driver.proxy # back to a direct connection
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Through the relay, HTTP proxies are used with `CONNECT` for every site,
|
|
169
|
+
`http://` ones included, so the proxy has to allow `CONNECT` to port 80.
|
|
170
|
+
|
|
171
|
+
## What works where
|
|
172
|
+
|
|
173
|
+
| | Status |
|
|
174
|
+
| --- | --- |
|
|
175
|
+
| Chrome, Edge | supported |
|
|
176
|
+
| Requests in iframes, new tabs and popups | captured |
|
|
177
|
+
| Firefox | not yet |
|
|
178
|
+
| Remote WebDriver and Selenium Grid | not yet |
|
|
179
|
+
| selenium-wire's undetected-chromedriver integration | not yet |
|
|
180
|
+
|
|
181
|
+
## Development
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
uv sync
|
|
185
|
+
uv run pytest
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The tests start a real Chrome against local test servers and proxies.
|
|
189
|
+
`CHROME_BINARY` picks the browser and `NETWIRE_NO_SANDBOX=1` adds
|
|
190
|
+
`--no-sandbox` for containers.
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
MIT
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
netwire/__init__.py,sha256=smNXXLqVX6DRYzaqcPuqGJChpekxamIv3JpUoK0B7JE,581
|
|
2
|
+
netwire/_backend.py,sha256=R_d9mAM77_B1cyeta6_76uQ99RF_mtAEAvnDZsfW_Ns,19982
|
|
3
|
+
netwire/_cdp.py,sha256=QjjWwes46tJO1wnV-ei3QUObTBBepWPyoxeuUcxK_Uo,4504
|
|
4
|
+
netwire/_config.py,sha256=aXORzjAgihaY6QuMrblv1ib1nx7gjLDL3E5ktDfrndk,4382
|
|
5
|
+
netwire/_har.py,sha256=7AWiSf1sJWoqPATJ591f57A9M7nypdkszKAHSS6CLKk,3025
|
|
6
|
+
netwire/_mixin.py,sha256=SoAjoFm2VaVkMYTF9ygwN_5Ufm9RVwAnPNY1yFwLzKE,4431
|
|
7
|
+
netwire/_relay.py,sha256=rwwl2tAy5za92Oq5lje2zug2n8igDY7K0guVQt5funM,9908
|
|
8
|
+
netwire/request.py,sha256=x7Sn8nB8-pXr4l1xi0M3UTW_VVnbPIXXkGM2PgKV5Bs,7630
|
|
9
|
+
netwire/utils.py,sha256=H3CQaMtEGS3QmJJ3Cs71psuPiYlJxwwg8tORuQRdx3w,1282
|
|
10
|
+
netwire/webdriver.py,sha256=KnBWSNMefEhSttthby1DteOVGg1Oy5XDSbN1HZJTwlg,2600
|
|
11
|
+
selenium_netwire-0.1.0.dist-info/METADATA,sha256=d9vQFvNXfzTLcRPt403649ExEeplnMpI_45vaNxFM3o,6808
|
|
12
|
+
selenium_netwire-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
selenium_netwire-0.1.0.dist-info/licenses/LICENSE,sha256=2RE-_vVtZEK01QWn9tqzUYzDB1gax-tYxzGjO_yCfYg,1074
|
|
14
|
+
selenium_netwire-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tugay Abdullazade
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|