Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use Chromium’s Chrome DevTools Protocol (CDP) through Selenium’s execute_cdp_cmd. Enable the Network domain, call Network.setBlockedURLs with wildcard URL patterns, and do it before driver.get() so the initial document and its subresources are covered.
The same technique can block image, stylesheet, font, video, tracker, API, host, path, or exact-URL requests. Keep the patterns narrow and verify the resulting page, because blocking CSS, JavaScript, fonts, or application APIs can change layout or stop the app from starting.
What you need before blocking requests
- Python and Selenium installed in the environment that runs the test.
- A Chromium-based browser and a Selenium driver configuration that can launch it.
- A representative page whose behavior you can assert after resources are blocked.
Network.setBlockedURLs is a Chromium CDP command. It is not a browser-neutral WebDriver command, so the implementation below is specifically for Chromium. The command accepts a list of URL patterns and supports * wildcards.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Complete Selenium Python example
This script blocks common image, stylesheet, font, and video extensions before opening the page. The finally block ensures the browser closes even when the page or an assertion fails.
#1 Best Overall
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
blocked_patterns = [
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"*.webp",
"*.css",
"*.woff",
"*.woff2",
"*.mp4",
]
try:
# Turn on the Network domain before installing blocking rules.
driver.execute_cdp_cmd("Network.enable", {})
driver.execute_cdp_cmd(
"Network.setBlockedURLs",
{"urls": blocked_patterns},
)
# Rules are active for this navigation and its subresources.
driver.get("https://example.com")
# Add assertions that describe the page state your test requires.
print(driver.title)
finally:
driver.quit()
Install the rules before navigation, not after the page has already loaded. Requests made during the initial document load can otherwise escape the block list. If a later test needs different rules, install the new list before its next navigation and verify that the page reaches the expected state.
Choosing URL patterns
Block a resource class by extension
Extension patterns are convenient when the purpose is to suppress a broad class of downloads:
blocked_patterns = [
"*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp",
"*.css", "*.woff", "*.woff2", "*.mp4",
]
A pattern such as *.css can match stylesheets from every origin visited by the page. That is useful for a deliberately unstyled test, but dangerous when your assertion depends on layout or visible-state styling.
Restrict blocking to one host
Use a host-and-path pattern when only one origin should be affected:
blocked_patterns = [
"*://cdn.example.com/*",
]
This is safer than a global extension rule when the application loads required assets from several domains. You can similarly target a path, such as *://example.com/analytics/*, when the test should suppress one service but leave the rest of the site intact.
Rank #2
Match one endpoint or URL family
For an individual endpoint, make the pattern as specific as practical:
blocked_patterns = [
"https://example.com/api/telemetry",
"*://example.com/ads/*",
]
Patterns are supplied in a list and are applied in the order supplied. Keep the list easy to audit: one reason per entry and comments explaining why a request is intentionally denied.
Common blocking recipes
Images only
driver.execute_cdp_cmd(
"Network.setBlockedURLs",
{"urls": ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp"]},
)
Use this for tests that do not inspect image pixels or image-driven layout. Responsive pages can still reserve image space, but the final rendering and timing may differ from a normal load.
Fonts only
driver.execute_cdp_cmd(
"Network.setBlockedURLs",
{"urls": ["*.woff", "*.woff2", "*.ttf", "*.otf"]},
)
The common .woff and .woff2 patterns are useful starting points. Add other font extensions only when you have confirmed that the target application uses them. Without web fonts, text metrics and wrapping can change.
Media files
driver.execute_cdp_cmd(
"Network.setBlockedURLs",
{"urls": ["*.mp4", "*.webm", "*.ogg"]},
)
Blocking media is appropriate for functional tests that do not exercise playback. A test that waits for a video element to become ready will need a different setup.
Rank #3
Trackers or advertising hosts
Prefer host or path patterns over a global extension list. For example:
blocked_patterns = [
"*://ads.example.net/*",
"*://metrics.example.net/collect/*",
]
Host-specific rules reduce the chance of blocking a first-party script or API that the application actually needs.
Blocking versus page-load strategy
Selenium’s page_load_strategy controls when navigation returns; it does not prevent a resource from being requested. The available behaviors differ in what navigation waits for:
| Setting | Navigation returns after | Does it block requests? | Typical use |
|---|---|---|---|
normal |
The load event | No | Use when the test expects the normal load lifecycle. |
eager |
DOMContentLoaded; images and other resources may still load | No | Return once the DOM is available while allowing remaining resources to continue. |
none |
The initial page download begins | No | Take control of synchronization yourself. |
Configure an earlier return separately from request blocking:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.page_load_strategy = "eager"
driver = webdriver.Chrome(options=options)
try:
driver.execute_cdp_cmd("Network.enable", {})
driver.execute_cdp_cmd(
"Network.setBlockedURLs",
{"urls": ["*.png", "*.jpg", "*.css"]},
)
driver.get("https://example.com")
finally:
driver.quit()
Use resource blocking when downloads themselves must not occur. Use eager or none when the page may continue loading but your test needs navigation to return earlier. They are complementary choices, not substitutes.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsRank #4
Verify that blocking worked
Inspect the Network panel
In Chrome DevTools, add the same request-blocking pattern, reload the page, and inspect the Network log. Blocked requests appear as blocked entries. This confirms that the pattern matches the actual URL rather than merely appearing plausible.
Assert page behavior in the test
Network evidence is not enough: assert the state your test is meant to cover. Examples include checking that a main heading is present, an application shell initializes, or a deliberately blocked optional widget is absent. Also watch for missing elements, failed initialization, and changed timing.
Control the cache during comparisons
A cached resource can make a before-and-after timing comparison misleading. Use a representative page and clear the browser cache when comparing blocked and unblocked runs, so a cached response does not hide the effect of the rule.
Failure modes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Nothing appears blocked | The rules were installed after navigation, or the pattern does not match the final URL. | Call Network.enable and Network.setBlockedURLs before get(); copy the exact request URL from the Network log and adjust the wildcard. |
| The page is unstyled or elements move | A stylesheet or font required for rendering was blocked. | Remove the broad CSS/font rule, or replace it with a host/path pattern that targets only optional assets. |
| The application stays blank or never becomes ready | A JavaScript bundle or API endpoint was denied. | Restore scripts and application API URLs. Block only optional telemetry, advertising, or media requests. |
| Timing results vary between runs | Cached assets, asynchronous requests, or a different navigation wait condition. | Clear the cache for comparisons, use the same page-load strategy, and synchronize on a page condition rather than an arbitrary sleep. |
| The CDP call fails | The session is not a compatible Chromium session or the command was misspelled. | Confirm that Selenium launched Chromium and use the exact command names Network.enable and Network.setBlockedURLs. |
| Navigation returns earlier than expected | eager or none was selected. |
Use normal, or add explicit waits for the DOM state your test needs. Changing page-load strategy does not restore blocked resources. |
Safer test design and maintenance
Start with the smallest rule set
Begin with one optional resource or one known host. Add patterns only after confirming that the test still represents the behavior you want. A global *.js or API rule can disable the application rather than merely making it faster.
Recommended Free Tools
Separate performance experiments from functional tests
A page rendered without images, CSS, or fonts is not equivalent to the user-facing page. Keep a named configuration for resource-blocking experiments and run a normal-load suite when visual or interaction fidelity matters.
Best Value
Record the reason for every rule
Blocking lists tend to outlive the test that created them. Comments and focused host/path patterns make it clear whether a rule removes advertising noise, avoids a third-party dependency, or models a constrained network.
Or skip the browser setup
If your goal is a clean screenshot rather than browser-level test assertions, ScreenshotNeo provides a single HTTP request. It can block ads, trackers, requests, or resource types, while also waiting for selectors, delays, or network idle when the page needs synchronization. Before capture it accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off.
Only clean shots are billed. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response identifies the result with X-Page-Verdict and X-Billed headers. ScreenshotNeo also has an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
See the ScreenshotNeo API documentation for the full parameter list. A basic cURL request is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The equivalent Python request is:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
And in Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The Free plan includes 1,000 shots each month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free, and every feature is included on every plan. Create a free ScreenshotNeo account.
FAQ
Does blocking a URL alter the server response?
No. The browser prevents the matching URL from loading. The server-side resource is unchanged; only this Chromium session omits the request.
Can I use the same rules to prove that a resource is optional?
Yes, but treat the result as an application test: after applying the rule, assert that the required page state still initializes. A request that looks optional can still provide CSS, JavaScript, fonts, or API data needed by the page.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Frequently Asked Questions
Does blocking a URL alter the server response?
No. The browser prevents the matching URL from loading; the server-side resource is unchanged.
Can I use the same rules to prove that a resource is optional?
Yes, but assert that the required page state still initializes after the block. A seemingly optional request may provide CSS, JavaScript, fonts, or API data the page needs.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

