playwright-blocker 1.0.0__tar.gz
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.
- playwright_blocker-1.0.0/LICENSE +28 -0
- playwright_blocker-1.0.0/PKG-INFO +154 -0
- playwright_blocker-1.0.0/README.md +114 -0
- playwright_blocker-1.0.0/pyproject.toml +71 -0
- playwright_blocker-1.0.0/setup.cfg +4 -0
- playwright_blocker-1.0.0/src/playwright_blocker/__init__.py +3 -0
- playwright_blocker-1.0.0/src/playwright_blocker/_blocking.py +112 -0
- playwright_blocker-1.0.0/src/playwright_blocker/_domains.py +3537 -0
- playwright_blocker-1.0.0/src/playwright_blocker/_types.py +42 -0
- playwright_blocker-1.0.0/src/playwright_blocker/py.typed +0 -0
- playwright_blocker-1.0.0/src/playwright_blocker.egg-info/PKG-INFO +154 -0
- playwright_blocker-1.0.0/src/playwright_blocker.egg-info/SOURCES.txt +17 -0
- playwright_blocker-1.0.0/src/playwright_blocker.egg-info/dependency_links.txt +1 -0
- playwright_blocker-1.0.0/src/playwright_blocker.egg-info/requires.txt +18 -0
- playwright_blocker-1.0.0/src/playwright_blocker.egg-info/top_level.txt +1 -0
- playwright_blocker-1.0.0/tests/test_blocking.py +187 -0
- playwright_blocker-1.0.0/tests/test_browser.py +148 -0
- playwright_blocker-1.0.0/tests/test_logging.py +134 -0
- playwright_blocker-1.0.0/tests/test_pages.py +74 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024, Karim shoair
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: playwright-blocker
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A plugin library for any Playwright-based library that allows blocking ads, domains, and resource types through injectors.
|
|
5
|
+
Author-email: Karim Shoair <karim.shoair@proton.me>
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Keywords: playwright,patchright,ads,tracking,browser,scraping
|
|
8
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest<9,>=8; extra == "test"
|
|
25
|
+
Requires-Dist: pytest-asyncio; extra == "test"
|
|
26
|
+
Requires-Dist: pytest-cov; extra == "test"
|
|
27
|
+
Requires-Dist: playwright==1.64.1; extra == "test"
|
|
28
|
+
Requires-Dist: patchright==1.64.4; extra == "test"
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: bandit[toml]>=1.9.0; extra == "dev"
|
|
31
|
+
Requires-Dist: ruff>=0.14.5; extra == "dev"
|
|
32
|
+
Requires-Dist: vermin>=1.7.0; extra == "dev"
|
|
33
|
+
Requires-Dist: mypy; extra == "dev"
|
|
34
|
+
Requires-Dist: pyright; extra == "dev"
|
|
35
|
+
Requires-Dist: build; extra == "dev"
|
|
36
|
+
Requires-Dist: twine; extra == "dev"
|
|
37
|
+
Requires-Dist: tox; extra == "dev"
|
|
38
|
+
Requires-Dist: pre-commit; extra == "dev"
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
# playwright-blocker
|
|
42
|
+
|
|
43
|
+
A plugin library for any Playwright-based library that allows blocking ads, domains, and resource types through injectors. Supports sync and async pages.
|
|
44
|
+
|
|
45
|
+
This library was ported from the blocking code inside [Scrapling](https://github.com/D4Vinci/Scrapling).
|
|
46
|
+
|
|
47
|
+
The package uses only the Python standard library.
|
|
48
|
+
|
|
49
|
+
## Install
|
|
50
|
+
|
|
51
|
+
Requires Python 3.10 or newer.
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
python -m pip install playwright-blocker
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Sync
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from playwright.sync_api import sync_playwright
|
|
61
|
+
from playwright_blocker import inject
|
|
62
|
+
|
|
63
|
+
with sync_playwright() as playwright:
|
|
64
|
+
browser = playwright.chromium.launch()
|
|
65
|
+
try:
|
|
66
|
+
context = browser.new_context(service_workers="block")
|
|
67
|
+
page = context.new_page()
|
|
68
|
+
inject(page)
|
|
69
|
+
page.goto("https://example.com")
|
|
70
|
+
print(page.title())
|
|
71
|
+
finally:
|
|
72
|
+
browser.close()
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Async
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import asyncio
|
|
79
|
+
|
|
80
|
+
from playwright.async_api import async_playwright
|
|
81
|
+
from playwright_blocker import inject_async
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
async def main():
|
|
85
|
+
async with async_playwright() as playwright:
|
|
86
|
+
browser = await playwright.chromium.launch()
|
|
87
|
+
try:
|
|
88
|
+
context = await browser.new_context(service_workers="block")
|
|
89
|
+
page = await context.new_page()
|
|
90
|
+
await inject_async(page)
|
|
91
|
+
await page.goto("https://example.com")
|
|
92
|
+
print(await page.title())
|
|
93
|
+
finally:
|
|
94
|
+
await browser.close()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
asyncio.run(main())
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
These examples use Playwright. The same `inject` and `inject_async` calls work with pages from any Playwright-based library.
|
|
101
|
+
|
|
102
|
+
## Options
|
|
103
|
+
|
|
104
|
+
Both functions take a page as their first argument. Set the other arguments by name.
|
|
105
|
+
|
|
106
|
+
| Argument | Default | Effect |
|
|
107
|
+
|---------------------|---------|--------------------------------------------------------------------------|
|
|
108
|
+
| `block_ads` | `True` | Block the bundled ad and tracking domains. |
|
|
109
|
+
| `blocked_domains` | `None` | Add domain names to block. Accepts a set or another iterable of strings. |
|
|
110
|
+
| `disable_resources` | `False` | Block the resource types listed below. |
|
|
111
|
+
|
|
112
|
+
Logging is automatic. Blocked requests are logged at `DEBUG` level.
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
handler = inject(
|
|
116
|
+
page,
|
|
117
|
+
blocked_domains={"ads.example.com", "tracker.example.net"},
|
|
118
|
+
disable_resources=True,
|
|
119
|
+
)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Use lowercase hostnames without a scheme, path or port. A domain also blocks its subdomains: `example.com` matches `cdn.example.com`, but does not match `notexample.com`. Input sets are copied and are not changed.
|
|
123
|
+
|
|
124
|
+
`disable_resources=True` blocks these resource types: `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`. Only resource types reported by the driver's HTTP route API can be blocked. This option does not intercept WebSocket connections.
|
|
125
|
+
|
|
126
|
+
To use only your own domains, pass `block_ads=False`. If all options are off, no route is added.
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
From this directory:
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
python -m pip install -e ".[test]" mypy pyright ruff build twine tox
|
|
134
|
+
python -m playwright install chromium
|
|
135
|
+
python -m patchright install chromium
|
|
136
|
+
python -m pytest
|
|
137
|
+
mypy src/
|
|
138
|
+
pyright
|
|
139
|
+
ruff check .
|
|
140
|
+
ruff format --check .
|
|
141
|
+
python -m build
|
|
142
|
+
python -m twine check dist/*
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
The browser tests run in sequence and use a local HTTP server. They check sync and async page routing and reject browser contexts.
|
|
146
|
+
|
|
147
|
+
## Domain list and license
|
|
148
|
+
|
|
149
|
+
The bundled domains were extracted from [Peter Lowe's ad and tracking server list](https://pgl.yoyo.org/adservers/), using its [plain hostname format](https://pgl.yoyo.org/adservers/serverlist.php?hostformat=plain&showintro=0&startyear=2000&mimetype=plaintext). Source credit is also kept in the data module.
|
|
150
|
+
|
|
151
|
+
The code is under the [BSD 3-Clause license](LICENSE).
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
<div align="center"><small>Designed & crafted with ❤️ by Karim Shoair.</small></div><br>
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# playwright-blocker
|
|
2
|
+
|
|
3
|
+
A plugin library for any Playwright-based library that allows blocking ads, domains, and resource types through injectors. Supports sync and async pages.
|
|
4
|
+
|
|
5
|
+
This library was ported from the blocking code inside [Scrapling](https://github.com/D4Vinci/Scrapling).
|
|
6
|
+
|
|
7
|
+
The package uses only the Python standard library.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
Requires Python 3.10 or newer.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
python -m pip install playwright-blocker
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Sync
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from playwright.sync_api import sync_playwright
|
|
21
|
+
from playwright_blocker import inject
|
|
22
|
+
|
|
23
|
+
with sync_playwright() as playwright:
|
|
24
|
+
browser = playwright.chromium.launch()
|
|
25
|
+
try:
|
|
26
|
+
context = browser.new_context(service_workers="block")
|
|
27
|
+
page = context.new_page()
|
|
28
|
+
inject(page)
|
|
29
|
+
page.goto("https://example.com")
|
|
30
|
+
print(page.title())
|
|
31
|
+
finally:
|
|
32
|
+
browser.close()
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Async
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import asyncio
|
|
39
|
+
|
|
40
|
+
from playwright.async_api import async_playwright
|
|
41
|
+
from playwright_blocker import inject_async
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def main():
|
|
45
|
+
async with async_playwright() as playwright:
|
|
46
|
+
browser = await playwright.chromium.launch()
|
|
47
|
+
try:
|
|
48
|
+
context = await browser.new_context(service_workers="block")
|
|
49
|
+
page = await context.new_page()
|
|
50
|
+
await inject_async(page)
|
|
51
|
+
await page.goto("https://example.com")
|
|
52
|
+
print(await page.title())
|
|
53
|
+
finally:
|
|
54
|
+
await browser.close()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
asyncio.run(main())
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
These examples use Playwright. The same `inject` and `inject_async` calls work with pages from any Playwright-based library.
|
|
61
|
+
|
|
62
|
+
## Options
|
|
63
|
+
|
|
64
|
+
Both functions take a page as their first argument. Set the other arguments by name.
|
|
65
|
+
|
|
66
|
+
| Argument | Default | Effect |
|
|
67
|
+
|---------------------|---------|--------------------------------------------------------------------------|
|
|
68
|
+
| `block_ads` | `True` | Block the bundled ad and tracking domains. |
|
|
69
|
+
| `blocked_domains` | `None` | Add domain names to block. Accepts a set or another iterable of strings. |
|
|
70
|
+
| `disable_resources` | `False` | Block the resource types listed below. |
|
|
71
|
+
|
|
72
|
+
Logging is automatic. Blocked requests are logged at `DEBUG` level.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
handler = inject(
|
|
76
|
+
page,
|
|
77
|
+
blocked_domains={"ads.example.com", "tracker.example.net"},
|
|
78
|
+
disable_resources=True,
|
|
79
|
+
)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Use lowercase hostnames without a scheme, path or port. A domain also blocks its subdomains: `example.com` matches `cdn.example.com`, but does not match `notexample.com`. Input sets are copied and are not changed.
|
|
83
|
+
|
|
84
|
+
`disable_resources=True` blocks these resource types: `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`. Only resource types reported by the driver's HTTP route API can be blocked. This option does not intercept WebSocket connections.
|
|
85
|
+
|
|
86
|
+
To use only your own domains, pass `block_ads=False`. If all options are off, no route is added.
|
|
87
|
+
|
|
88
|
+
## Development
|
|
89
|
+
|
|
90
|
+
From this directory:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
python -m pip install -e ".[test]" mypy pyright ruff build twine tox
|
|
94
|
+
python -m playwright install chromium
|
|
95
|
+
python -m patchright install chromium
|
|
96
|
+
python -m pytest
|
|
97
|
+
mypy src/
|
|
98
|
+
pyright
|
|
99
|
+
ruff check .
|
|
100
|
+
ruff format --check .
|
|
101
|
+
python -m build
|
|
102
|
+
python -m twine check dist/*
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The browser tests run in sequence and use a local HTTP server. They check sync and async page routing and reject browser contexts.
|
|
106
|
+
|
|
107
|
+
## Domain list and license
|
|
108
|
+
|
|
109
|
+
The bundled domains were extracted from [Peter Lowe's ad and tracking server list](https://pgl.yoyo.org/adservers/), using its [plain hostname format](https://pgl.yoyo.org/adservers/serverlist.php?hostformat=plain&showintro=0&startyear=2000&mimetype=plaintext). Source credit is also kept in the data module.
|
|
110
|
+
|
|
111
|
+
The code is under the [BSD 3-Clause license](LICENSE).
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
<div align="center"><small>Designed & crafted with ❤️ by Karim Shoair.</small></div><br>
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "playwright-blocker"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "A plugin library for any Playwright-based library that allows blocking ads, domains, and resource types through injectors."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "BSD-3-Clause"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{name = "Karim Shoair", email = "karim.shoair@proton.me"}]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
dependencies = []
|
|
15
|
+
keywords = ["playwright", "patchright", "ads", "tracking", "browser", "scraping"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 5 - Production/Stable",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Topic :: Internet :: WWW/HTTP :: Browsers",
|
|
27
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
test = [
|
|
33
|
+
"pytest>=8,<9",
|
|
34
|
+
"pytest-asyncio",
|
|
35
|
+
"pytest-cov",
|
|
36
|
+
"playwright==1.64.1",
|
|
37
|
+
"patchright==1.64.4",
|
|
38
|
+
]
|
|
39
|
+
dev = [
|
|
40
|
+
"bandit[toml]>=1.9.0",
|
|
41
|
+
"ruff>=0.14.5",
|
|
42
|
+
"vermin>=1.7.0",
|
|
43
|
+
"mypy",
|
|
44
|
+
"pyright",
|
|
45
|
+
"build",
|
|
46
|
+
"twine",
|
|
47
|
+
"tox",
|
|
48
|
+
"pre-commit",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.packages.find]
|
|
52
|
+
where = ["src"]
|
|
53
|
+
|
|
54
|
+
[tool.setuptools.package-data]
|
|
55
|
+
playwright_blocker = ["py.typed"]
|
|
56
|
+
|
|
57
|
+
[tool.pytest.ini_options]
|
|
58
|
+
testpaths = ["tests"]
|
|
59
|
+
asyncio_mode = "strict"
|
|
60
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
61
|
+
markers = ["browser: tests that start a real browser"]
|
|
62
|
+
|
|
63
|
+
[tool.mypy]
|
|
64
|
+
python_version = "3.10"
|
|
65
|
+
files = ["src"]
|
|
66
|
+
strict = true
|
|
67
|
+
|
|
68
|
+
[tool.pyright]
|
|
69
|
+
pythonVersion = "3.10"
|
|
70
|
+
typeCheckingMode = "strict"
|
|
71
|
+
include = ["src"]
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from collections.abc import Awaitable, Callable, Iterable
|
|
2
|
+
from logging import INFO, Formatter, Logger, StreamHandler, getLogger
|
|
3
|
+
from urllib.parse import urlparse
|
|
4
|
+
|
|
5
|
+
from ._types import AsyncPage, AsyncRoute, Request, SyncPage, SyncRoute
|
|
6
|
+
|
|
7
|
+
EXTRA_RESOURCES = frozenset(
|
|
8
|
+
{"font", "image", "media", "beacon", "object", "imageset", "texttrack", "websocket", "csp_report", "stylesheet"}
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _validate_page(page: SyncPage | AsyncPage) -> None:
|
|
13
|
+
if getattr(page, "context", None) is None or not callable(getattr(page, "route", None)):
|
|
14
|
+
raise TypeError("Expected a Playwright-compatible Page.")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _get_logger() -> Logger:
|
|
18
|
+
if isinstance(Logger.manager.loggerDict.get("scrapling"), Logger):
|
|
19
|
+
return getLogger("scrapling")
|
|
20
|
+
logger = getLogger("playwright_blocker")
|
|
21
|
+
if not logger.handlers:
|
|
22
|
+
logger.setLevel(INFO)
|
|
23
|
+
handler = StreamHandler()
|
|
24
|
+
handler.setFormatter(Formatter("[%(asctime)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S"))
|
|
25
|
+
logger.addHandler(handler)
|
|
26
|
+
return logger
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _is_domain_blocked(hostname: str, domains: frozenset[str]) -> bool:
|
|
30
|
+
"""Check if a hostname matches any blocked domain using O(1) frozenset lookups.
|
|
31
|
+
|
|
32
|
+
Walks up the hostname's suffix chain: for "tracker.ads.doubleclick.net",
|
|
33
|
+
checks "tracker.ads.doubleclick.net", "ads.doubleclick.net", "doubleclick.net".
|
|
34
|
+
|
|
35
|
+
:param hostname: The hostname to check.
|
|
36
|
+
:param domains: A frozenset of blocked domain names.
|
|
37
|
+
:return: True if the hostname or any of its parent domains is in the blocked set.
|
|
38
|
+
"""
|
|
39
|
+
if hostname in domains:
|
|
40
|
+
return True
|
|
41
|
+
idx = hostname.find(".")
|
|
42
|
+
while idx != -1:
|
|
43
|
+
suffix = hostname[idx + 1 :]
|
|
44
|
+
if "." in suffix and suffix in domains:
|
|
45
|
+
return True
|
|
46
|
+
idx = hostname.find(".", idx + 1)
|
|
47
|
+
return False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _domains(block_ads: bool, blocked_domains: Iterable[str] | None) -> frozenset[str]:
|
|
51
|
+
domains = frozenset(blocked_domains or ())
|
|
52
|
+
if block_ads:
|
|
53
|
+
from ._domains import AD_DOMAINS
|
|
54
|
+
|
|
55
|
+
domains |= AD_DOMAINS
|
|
56
|
+
return domains
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _blocked(request: Request, disable_resources: bool, domains: frozenset[str], logger: Logger) -> bool:
|
|
60
|
+
if disable_resources and request.resource_type in EXTRA_RESOURCES:
|
|
61
|
+
logger.debug(f'Blocking background resource "{request.url}" of type "{request.resource_type}"')
|
|
62
|
+
return True
|
|
63
|
+
if domains and _is_domain_blocked(hostname := urlparse(request.url).hostname or "", domains):
|
|
64
|
+
logger.debug(f'Blocking request to blocked domain "{hostname}" ({request.url})')
|
|
65
|
+
return True
|
|
66
|
+
return False
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def inject(
|
|
70
|
+
page: SyncPage,
|
|
71
|
+
*,
|
|
72
|
+
block_ads: bool = True,
|
|
73
|
+
blocked_domains: Iterable[str] | None = None,
|
|
74
|
+
disable_resources: bool = False,
|
|
75
|
+
) -> Callable[[SyncRoute], None]:
|
|
76
|
+
"""Install blocking on a sync page and return its removable route handler."""
|
|
77
|
+
_validate_page(page)
|
|
78
|
+
domains = _domains(block_ads, blocked_domains)
|
|
79
|
+
log = _get_logger()
|
|
80
|
+
|
|
81
|
+
def handler(route: SyncRoute) -> None:
|
|
82
|
+
if _blocked(route.request, disable_resources, domains, log):
|
|
83
|
+
route.abort()
|
|
84
|
+
else:
|
|
85
|
+
route.continue_()
|
|
86
|
+
|
|
87
|
+
if disable_resources or domains:
|
|
88
|
+
page.route("**/*", handler)
|
|
89
|
+
return handler
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def inject_async(
|
|
93
|
+
page: AsyncPage,
|
|
94
|
+
*,
|
|
95
|
+
block_ads: bool = True,
|
|
96
|
+
blocked_domains: Iterable[str] | None = None,
|
|
97
|
+
disable_resources: bool = False,
|
|
98
|
+
) -> Callable[[AsyncRoute], Awaitable[None]]:
|
|
99
|
+
"""Install blocking on an async page and return its removable route handler."""
|
|
100
|
+
_validate_page(page)
|
|
101
|
+
domains = _domains(block_ads, blocked_domains)
|
|
102
|
+
log = _get_logger()
|
|
103
|
+
|
|
104
|
+
async def handler(route: AsyncRoute) -> None:
|
|
105
|
+
if _blocked(route.request, disable_resources, domains, log):
|
|
106
|
+
await route.abort()
|
|
107
|
+
else:
|
|
108
|
+
await route.continue_()
|
|
109
|
+
|
|
110
|
+
if disable_resources or domains:
|
|
111
|
+
await page.route("**/*", handler)
|
|
112
|
+
return handler
|