> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zenrows.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Block Resources

> Block images, stylesheets, fonts, and other unnecessary resources during web scraping to reduce bandwidth and speed up page load times.

The Block Resources parameter prevents your headless browser from downloading specific types of content that aren't essential for your scraping task. By blocking unnecessary resources, such as images, stylesheets, fonts, and media files, you can significantly improve scraping efficiency, reduce loading times, optimize performance, and minimize bandwidth usage.

When you block resources, ZenRows instructs the browser to ignore requests for the specified content types, allowing pages to load faster and consume less data. This is particularly valuable when scraping content-heavy sites where you only need the text data or specific elements.

<Warning>ZenRows automatically blocks certain resource types by default, such as stylesheets and images, to optimize scraping speed and reduce unnecessary data load. **We recommend only using this parameter when you need to customize the default blocking behavior or when troubleshooting specific issues.**</Warning>

## How Block Resources works

Block Resources operates at the network level within the browser, intercepting requests for specified resource types before they're downloaded. When the browser encounters a request for a blocked resource type, it prevents the download entirely, reducing both loading time and bandwidth consumption.

This process affects:

* Page loading speed by eliminating unnecessary downloads
* Bandwidth usage by preventing large file transfers
* Memory consumption by reducing the amount of data processed
* Rendering time by focusing only on essential content
* Network request volume by filtering out non-critical resources

The blocking happens transparently during page rendering, ensuring that essential functionality remains intact while removing unnecessary overhead.

## Basic usage

Add the `block_resources` parameter with comma-separated resource types to your request:

<CodeGroup>
  ```python Python theme={null}
  # pip install requests
  import requests

  url = 'https://httpbin.io/anything'
  apikey = 'YOUR_ZENROWS_API_KEY'
  params = {
      'url': url,
      'apikey': apikey,
      'js_render': 'true',
      'block_resources': 'image,media,font',
  }
  response = requests.get('https://api.zenrows.com/v1/', params=params)
  print(response.text)
  ```

  ```javascript Node.js theme={null}
  // npm install axios
  const axios = require('axios');

  const url = 'https://httpbin.io/anything';
  const apikey = 'YOUR_ZENROWS_API_KEY';
  axios({
      url: 'https://api.zenrows.com/v1/',
      method: 'GET',
      params: {
          'url': url,
          'apikey': apikey,
          'js_render': 'true',
          'block_resources': 'image,media,font',
      },
  })
      .then(response => console.log(response.data))
      .catch(error => console.log(error));
  ```

  ```java Java theme={null}
  import org.apache.hc.client5.http.fluent.Request;

  public class APIRequest {
      public static void main(final String... args) throws Exception {
          String apiUrl = "https://api.zenrows.com/v1/?apikey=YOUR_ZENROWS_API_KEY&url=https%3A%2F%2Fhttpbin.io%2Fanything&js_render=true&block_resources=image%2Cmedia%2Cfont";
          String response = Request.get(apiUrl)
                  .execute().returnContent().asString();

          System.out.println(response);
      }
  }
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'https://api.zenrows.com/v1/?apikey=YOUR_ZENROWS_API_KEY&url=https%3A%2F%2Fhttpbin.io%2Fanything&js_render=true&block_resources=image%2Cmedia%2Cfont');
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $response = curl_exec($ch);
  echo $response . PHP_EOL;
  curl_close($ch);
  ?>
  ```

  ```go Go theme={null}
  package main

  import (
      "io"
      "log"
      "net/http"
  )

  func main() {
      client := &http.Client{}
      req, err := http.NewRequest("GET", "https://api.zenrows.com/v1/?apikey=YOUR_ZENROWS_API_KEY&url=https%3A%2F%2Fhttpbin.io%2Fanything&js_render=true&block_resources=image%2Cmedia%2Cfont", nil)
      if err != nil {
          log.Fatalln(err)
      }
      resp, err := client.Do(req)
      if err != nil {
          log.Fatalln(err)
      }
      defer resp.Body.Close()

      body, err := io.ReadAll(resp.Body)
      if err != nil {
          log.Fatalln(err)
      }

      log.Println(string(body))
  }
  ```

  ```ruby Ruby theme={null}
  # gem install faraday
  require 'faraday'

  url = URI.parse('https://api.zenrows.com/v1/?apikey=YOUR_ZENROWS_API_KEY&url=https%3A%2F%2Fhttpbin.io%2Fanything&js_render=true&block_resources=image%2Cmedia%2Cfont')
  conn = Faraday.new()
  conn.options.timeout = 180
  res = conn.get(url, nil, nil)
  print(res.body)
  ```

  ```bash cURL theme={null}
  curl "https://api.zenrows.com/v1/?apikey=YOUR_ZENROWS_API_KEY&url=https%3A%2F%2Fhttpbin.io%2Fanything&js_render=true&block_resources=image%2Cmedia%2Cfont"
  ```
</CodeGroup>

This example blocks images, media files, and fonts while allowing other resources to load normally, resulting in faster page loading and reduced data usage.

## Available resource types

ZenRows supports blocking the following resource types:

### Content resources

* `stylesheet` - CSS files that define visual styling and layout
* `image` - All image formats including JPG, PNG, GIF, SVG, and WebP
* `media` - Audio and video files of all formats
* `font` - Web fonts including WOFF, WOFF2, TTF, and OTF files

### Script and dynamic content

* `script` - JavaScript files and inline scripts
* `xhr` - XMLHttpRequest calls used for AJAX functionality
* `fetch` - Modern Fetch API requests for dynamic content loading
* `eventsource` - Server-sent events for real-time data streams
* `websocket` - WebSocket connections for bidirectional communication

### Application resources

* `texttrack` - Video subtitle and caption files
* `manifest` - Web app manifests containing application metadata
* `other` - Any resource types not specifically categorized above

### Special values

* `none` - Disables all resource blocking, allowing everything to load

## When to use Block Resources

Block Resources is essential for these scenarios:

### Performance optimization:

* **Large-scale scraping** - Reduce bandwidth and processing time across many requests
* **Content-heavy sites** - Skip images and media when extracting text data
* **Slow connections** - Minimize data transfer in bandwidth-limited environments
* **High-volume operations** - Optimize resource usage for continuous scraping tasks
* **Cost reduction** - Lower bandwidth costs for cloud-based scraping operations

### Content-specific extraction:

* **Text-only scraping** - Extract articles, reviews, or descriptions without visual elements
* **Data mining** - Focus on structured data while ignoring presentation layers
* **API monitoring** - Allow dynamic requests while blocking static resources
* **Search engine optimization** - Analyze content structure without styling interference
* **Accessibility testing** - Test content availability without visual dependencies

### Troubleshooting and debugging:

* **JavaScript conflicts** - Isolate issues by selectively blocking script types
* **Loading problems** - Identify problematic resources causing page failures
* **Performance analysis** - Measure impact of different resource types on loading speed
* **Content validation** - Verify that essential content doesn't depend on blocked resources

## Disabling resource blocking

To turn off ZenRows' default resource blocking and allow all content to load:

```python Python theme={null}
params = {
    'js_render': 'true',
    'block_resources': 'none',  # Disable all resource blocking
}
```

Use `block_resources=none` when:

* You need complete visual fidelity
* Debugging layout or styling issues
* Testing how pages appear to real users
* Analyzing complete resource loading patterns
* Ensuring no content dependencies are missed

## Best practices

### Monitor content integrity

Verify that blocked resources don't affect essential content:

```python Python theme={null}
def validate_content_integrity(url, target_selectors):
    # Compare content availability with and without resource blocking

    from bs4 import BeautifulSoup
    
    # Test with default blocking
    default_response = requests.get('https://api.zenrows.com/v1/', params={
        'url': url,
        'apikey': 'YOUR_ZENROWS_API_KEY',
        'js_render': 'true',
    })
    
    # Test with aggressive blocking
    aggressive_response = requests.get('https://api.zenrows.com/v1/', params={
        'url': url,
        'apikey': 'YOUR_ZENROWS_API_KEY',
        'js_render': 'true',
        'block_resources': 'image,media,font,stylesheet,script',
    })
    
    default_soup = BeautifulSoup(default_response.text, 'html.parser')
    aggressive_soup = BeautifulSoup(aggressive_response.text, 'html.parser')
    
    integrity_report = {}
    
    for selector in target_selectors:
        default_elements = default_soup.select(selector)
        aggressive_elements = aggressive_soup.select(selector)
        
        integrity_report[selector] = {
            'default_count': len(default_elements),
            'aggressive_count': len(aggressive_elements),
            'content_preserved': len(default_elements) == len(aggressive_elements),
        }
    
    return integrity_report

# Validate that important content is preserved
selectors = ['.product-title', '.price', '.description', '.reviews']
integrity = validate_content_integrity('https://ecommerce.com/product/123', selectors)

for selector, data in integrity.items():
    status = "✓" if data['content_preserved'] else "✗"
    print(f"{status} {selector}: {data['default_count']} → {data['aggressive_count']} elements")
```

### Combine with other parameters

Use Block Resources with complementary features for optimal results:

```python Python theme={null}
params = {
    'js_render': 'true',
    'block_resources': 'image,media,font,stylesheet',  # Block visual resources
    'wait_for': '.main-content',                       # Wait for essential content
    'json_response': 'true',                          # Capture API calls
    'premium_proxy': 'true',                          # For protected sites
}
```

## Troubleshooting

### Common issues and solutions

| Issue             | Cause                      | Solution                               |
| ----------------- | -------------------------- | -------------------------------------- |
| Missing content   | Essential scripts blocked  | Remove `script` from blocked resources |
| Incomplete data   | XHR/Fetch requests blocked | Allow `xhr` and `fetch` resources      |
| Layout issues     | CSS dependencies           | Remove `stylesheet` from blocking      |
| Slow loading      | Too many resources allowed | Add more resource types to blocking    |
| JavaScript errors | Font or media dependencies | Test with individual resource types    |

### Debugging missing content

When content disappears after blocking resources:

<Steps>
  <Step title="Compare HTML outputs">
    Compare the HTML obtained with and without resource blocking to identify missing elements.

    ```python Python theme={null}
    # Get baseline without custom blocking
    baseline = requests.get('https://api.zenrows.com/v1/', params={
        'url': url,
        'apikey': 'YOUR_ZENROWS_API_KEY',
        'js_render': 'true',
    })
    # Get result with blocking
    blocked = requests.get('https://api.zenrows.com/v1/', params={
        'url': url,
        'apikey': 'YOUR_ZENROWS_API_KEY',
        'js_render': 'true',
        'block_resources': 'image,media,font,script',
    })

    print(f"Baseline length: {len(baseline.text)}")
    print(f"Blocked length: {len(blocked.text)}")
    ```
  </Step>

  <Step title="Test individual resource types">
    Block one resource type at a time to identify the problematic category.

    ```python Python theme={null}
    resource_types = ['image', 'media', 'font', 'stylesheet', 'script', 'xhr']

    for resource_type in resource_types:
        response = requests.get('https://api.zenrows.com/v1/', params={
            'url': url,
            'apikey': 'YOUR_ZENROWS_API_KEY',
            'js_render': 'true',
            'block_resources': resource_type,
        })
        
        # Check if target content exists
        has_content = 'target-selector' in response.text
        print(f"Blocking {resource_type}: Content present = {has_content}")
    ```
  </Step>

  <Step title="Adjust blocking strategy">
    Remove problematic resource types from your blocking configuration.

    ```python Python theme={null}
    # If script blocking causes issues, exclude it

    safe_blocking = 'image,media,font,stylesheet'  # Exclude script, xhr, fetch
    response = requests.get('https://api.zenrows.com/v1/', params={
        'url': url,
        'apikey': 'YOUR_ZENROWS_API_KEY',
        'js_render': 'true',
        'block_resources': safe_blocking,
    })
    ```
  </Step>
</Steps>

### Performance vs. content trade-offs

Balance optimization with content completeness:

```python Python theme={null}
def find_optimal_blocking(url, required_selectors):
    # Find the most aggressive blocking that preserves required content

    blocking_configurations = [
        'image',
        'image,media',
        'image,media,font',
        'image,media,font,stylesheet',
        'image,media,font,stylesheet,other',
    ]
    
    optimal_config = None
    
    for config in blocking_configurations:
        response = requests.get('https://api.zenrows.com/v1/', params={
            'url': url,
            'apikey': 'YOUR_ZENROWS_API_KEY',
            'js_render': 'true',
            'block_resources': config,
        })
        
        from bs4 import BeautifulSoup
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Check if all required content is present
        all_content_present = all(
            soup.select(selector) for selector in required_selectors
        )
        
        if all_content_present:
            optimal_config = config
            print(f"✓ Configuration '{config}' preserves all content")
        else:
            print(f"✗ Configuration '{config}' missing content")
            break
    
    return optimal_config

# Find optimal blocking for specific content requirements
required_elements = ['.product-title', '.price', '.description']
best_config = find_optimal_blocking('https://shop.com/product/123', required_elements)
print(f"Recommended blocking: {best_config}")
```

## Pricing

The `block_resources` parameter doesn't increase the request cost. You pay the JavaScript Render (5 times the standard price) regardless of the wait value you choose.

<Tip>
  You can monitor your ZenRows usage in multiple ways to stay informed about your account activity and prevent unexpected overages.

  **Dashboard monitoring**: View real-time usage statistics, remaining requests, success rates, and request history on your [Analytics Page](https://app.zenrows.com/analytics/scraper-api). You can also set up usage alerts in your [notification settings](https://app.zenrows.com/account/notifications) to receive notifications when you approach your limits.

  **Programmatic monitoring**: For automated monitoring in your applications, call the `/v1/subscriptions/self/details` endpoint with your API key in the `X-API-Key` header. This returns real-time usage data that you can integrate into your monitoring systems. [Learn more about the usage endpoint](https://docs.zenrows.com/universal-scraper-api/features/other#plan-usage).

  **Response header monitoring**: Track your concurrency usage through response headers included with each request:

  * `Concurrency-Limit`: Your maximum concurrent requests
  * `Concurrency-Remaining`: Available concurrent request slots
  * `X-Request-Cost`: Cost of the current request
</Tip>

## Frequently Asked Questions (FAQ)

<Accordion title="What resources does ZenRows block by default?">
  ZenRows automatically blocks stylesheets and images by default to optimize scraping speed and reduce data usage. You can override this behavior by setting `block_resources=none` to allow all resources, or by specifying custom blocking for specific resource types.
</Accordion>

<Accordion title="Will blocking JavaScript break dynamic content loading?">
  Yes, blocking scripts can prevent dynamic content from loading properly. If you need content that's loaded via JavaScript, avoid blocking the `script`, `xhr`, and `fetch` resource types. Focus on blocking visual resources like `image`, `media`, `font`, and `stylesheet` instead.
</Accordion>

<Accordion title="How much bandwidth can I save by blocking resources?">
  Bandwidth savings vary significantly depending on the website's content and design. Image-heavy sites can significantly reduce data transfer by blocking images and media. Text-focused sites may achieve savings by blocking stylesheets and fonts.
</Accordion>

<Accordion title="Can I block resources when not using js_render?">
  No, the `block_resources` parameter only works with `js_render=true` because resource blocking operates within the browser environment during JavaScript rendering. For static HTML requests, resource blocking isn't applicable.
</Accordion>

<Accordion title="What happens if I block XHR or Fetch requests?">
  Blocking XHR or Fetch requests prevents the page from making AJAX calls, which can result in missing dynamic content. Only block these if you're certain the content you need is available in the initial HTML without requiring additional API calls.
</Accordion>

<Accordion title="Does blocking resources affect the JSON Response feature?">
  Yes, if you block `xhr` or `fetch` resources, those requests won't appear in the JSON Response XHR array. However, blocking visual resources, such as images and stylesheets, won't affect the capture of API calls and can reduce the overall response size.
</Accordion>

<Accordion title="Can I use wildcards or patterns in resource blocking?">
  No, you must specify exact resource type names from the supported list. You cannot use wildcards or custom patterns. To block multiple types, separate them with commas, such as `image,media,font`.
</Accordion>

<Accordion title="How do I know which resources are safe to block for my use case?">
  Start by blocking only visual resources (`image,media,font,stylesheet`) and test if your target content is still available. If content is missing, remove resource types one by one until you find the minimal blocking configuration that preserves your required data.
</Accordion>
