Why use proxies with Scrapy?

Scrapy is the most powerful Python web scraping framework. When combined with DataSea proxies through custom middleware, you can scrape at massive scale with automatic IP rotation, geo-targeting, and retry logic.

Prerequisites

  • Python 3.8 or higher installed
  • Basic Scrapy knowledge
  • DataSea account with proxy credentials
  • Understanding of Scrapy middleware

Setup guide

  1. 01

    Get your DataSea credentials

    Sign in to your DataSea dashboard and copy your proxy credentials.

    text
    # DataSea Proxy Configuration
    Proxy Host: pr.datasea.io
    HTTP Port: 7011 (for http:// and https:// websites)
    HTTPS-to-proxy Port: 7010 (TLS between your client and the proxy)
    
    # Your credentials
    Username: your_proxy_username
    Password: your_16_char_password
    
    # Proxy URL formats
    http://username:password@pr.datasea.io:7011
    http://username_country-UnitedStates:password@pr.datasea.io:7011
    http://username_session-abc123:password@pr.datasea.io:7011
  2. 02

    Install Scrapy

    Create a new Scrapy project or use an existing one.

    bash
    # Install Scrapy
    pip install scrapy
    
    # Create a new project
    scrapy startproject myproject
    cd myproject
    
    # Create a spider
    scrapy genspider example example.com
  3. 03

    Create proxy middleware

    Create a custom middleware to inject DataSea proxy into requests.

    python
    # myproject/middlewares.py
    
    import base64
    
    class DataSeaProxyMiddleware:
        """
        Scrapy middleware for DataSea proxy integration.
        Adds proxy authentication to all requests.
        """
    
        def __init__(self, proxy_host, proxy_port, proxy_user, proxy_pass):
            self.proxy_url = f'http://{proxy_host}:{proxy_port}'
            self.proxy_auth = base64.b64encode(
                f'{proxy_user}:{proxy_pass}'.encode()
            ).decode()
    
        @classmethod
        def from_crawler(cls, crawler):
            return cls(
                proxy_host=crawler.settings.get('DATASEA_PROXY_HOST', 'pr.datasea.io'),
                proxy_port=crawler.settings.get('DATASEA_PROXY_PORT', '7011'),
                proxy_user=crawler.settings.get('DATASEA_PROXY_USER'),
                proxy_pass=crawler.settings.get('DATASEA_PROXY_PASS'),
            )
    
        def process_request(self, request, spider):
            request.meta['proxy'] = self.proxy_url
            request.headers['Proxy-Authorization'] = f'Basic {self.proxy_auth}'
            return None
  4. 04

    Configure settings

    Update your Scrapy settings to enable the proxy middleware.

    python
    # myproject/settings.py
    
    # DataSea Proxy Settings
    DATASEA_PROXY_HOST = 'pr.datasea.io'
    DATASEA_PROXY_PORT = '7011'
    DATASEA_PROXY_USER = 'your_username'  # Add _country-UnitedStates for geo-targeting
    DATASEA_PROXY_PASS = 'your_password'
    
    # Enable the middleware
    DOWNLOADER_MIDDLEWARES = {
        'myproject.middlewares.DataSeaProxyMiddleware': 350,
    }
    
    # Recommended settings for proxy usage
    CONCURRENT_REQUESTS = 16
    DOWNLOAD_DELAY = 0.5
    RETRY_TIMES = 3
    RETRY_HTTP_CODES = [500, 502, 503, 504, 408, 429]
    
    # Disable cookies if not needed (reduces fingerprinting)
    COOKIES_ENABLED = False
    
    # Rotate User-Agent
    USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'

Key features

Global coverage

Access 195+ countries with residential, datacenter, ISP, and mobile proxies.

Automatic rotation

Get new IPs automatically or use sticky sessions for crawling.

High performance

Handle concurrent requests efficiently with Scrapy's async architecture.

Middleware integration

Simple middleware pattern integrates seamlessly with Scrapy.

Built-in retries

Automatic retry logic for failed requests with new proxy IPs.

Geo-targeting

Target specific countries for localized content scraping.

Common use cases

Basic spider with proxy

A simple spider that uses DataSea proxies for all requests.

python
# myproject/spiders/example.py

import scrapy

class ExampleSpider(scrapy.Spider):
    name = 'example'
    start_urls = ['https://httpbin.org/ip']

    def parse(self, response):
        # This will show your proxy IP
        ip_data = response.json()
        self.logger.info(f"Request made from IP: {ip_data['origin']}")

        yield {
            'ip': ip_data['origin'],
            'url': response.url,
        }

# Run with: scrapy crawl example

Geo-targeted middleware

Enhanced middleware that supports country targeting per request.

python
# myproject/middlewares.py

import base64

class DataSeaGeoProxyMiddleware:
    """
    Advanced middleware with geo-targeting support.
    Set request.meta['country'] to target specific countries.
    """

    def __init__(self, proxy_host, proxy_port, proxy_user, proxy_pass):
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.base_user = proxy_user
        self.proxy_pass = proxy_pass

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            proxy_host=crawler.settings.get('DATASEA_PROXY_HOST', 'pr.datasea.io'),
            proxy_port=crawler.settings.get('DATASEA_PROXY_PORT', '7011'),
            proxy_user=crawler.settings.get('DATASEA_PROXY_USER'),
            proxy_pass=crawler.settings.get('DATASEA_PROXY_PASS'),
        )

    def process_request(self, request, spider):
        # Build username with targeting params
        username = self.base_user

        # Add country if specified
        country = request.meta.get('country')
        if country:
            username = f'{username}_country-{country}'

        # Add session if specified
        session_id = request.meta.get('session_id')
        if session_id:
            username = f'{username}_session-{session_id}'

        # Set proxy
        proxy_url = f'http://{self.proxy_host}:{self.proxy_port}'
        auth = base64.b64encode(f'{username}:{self.proxy_pass}'.encode()).decode()

        request.meta['proxy'] = proxy_url
        request.headers['Proxy-Authorization'] = f'Basic {auth}'

        return None

# Usage in spider:
# yield scrapy.Request(url, meta={'country': 'US'})

E-commerce price scraping

Scrape product prices from multiple countries.

python
# myproject/spiders/prices.py

import scrapy

class PriceSpider(scrapy.Spider):
    name = 'prices'
    countries = ['US', 'GB', 'DE', 'FR', 'JP']

    def start_requests(self):
        for country in self.countries:
            yield scrapy.Request(
                url='https://example-store.com/product/123',
                callback=self.parse_price,
                meta={
                    'country': country,
                    'dont_redirect': True,
                },
                cb_kwargs={'country': country}
            )

    def parse_price(self, response, country):
        price = response.css('.price::text').get()
        currency = response.css('.currency::text').get()

        yield {
            'country': country,
            'price': price,
            'currency': currency,
            'url': response.url,
        }

Session-based crawling

Use sticky sessions for sites that track user sessions.

python
# myproject/spiders/session_spider.py

import scrapy
import uuid

class SessionSpider(scrapy.Spider):
    name = 'session_spider'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Generate unique session ID for this crawl
        self.session_id = str(uuid.uuid4())[:8]

    def start_requests(self):
        # All requests use the same IP
        yield scrapy.Request(
            url='https://example.com/login',
            callback=self.parse_login,
            meta={
                'session_id': self.session_id,
                'country': 'US'
            }
        )

    def parse_login(self, response):
        # Submit login form
        yield scrapy.FormRequest.from_response(
            response,
            formdata={'user': 'myuser', 'pass': 'mypass'},
            callback=self.after_login,
            meta={
                'session_id': self.session_id,
                'country': 'US'
            }
        )

    def after_login(self, response):
        # Continue crawling with same session/IP
        for url in response.css('a.product::attr(href)').getall():
            yield scrapy.Request(
                url=response.urljoin(url),
                callback=self.parse_product,
                meta={
                    'session_id': self.session_id,
                    'country': 'US'
                }
            )

    def parse_product(self, response):
        yield {
            'title': response.css('h1::text').get(),
            'price': response.css('.price::text').get(),
        }

Troubleshooting

407 Proxy Authentication Required

Solution: Ensure your middleware is correctly setting the Proxy-Authorization header.

python
# Make sure credentials are correct
import base64

proxy_user = 'your_username'
proxy_pass = 'your_password'

# Correct encoding
auth = base64.b64encode(f'{proxy_user}:{proxy_pass}'.encode()).decode()
request.headers['Proxy-Authorization'] = f'Basic {auth}'

# Verify in settings.py
DATASEA_PROXY_USER = 'your_username'
DATASEA_PROXY_PASS = 'your_password'  # 16 characters from dashboard

Connection Timeout Errors

Solution: Adjust timeout settings and reduce concurrent requests.

python
# settings.py

# Increase timeouts
DOWNLOAD_TIMEOUT = 60

# Reduce concurrent requests if getting timeouts
CONCURRENT_REQUESTS = 8
CONCURRENT_REQUESTS_PER_DOMAIN = 4

# Add delay between requests
DOWNLOAD_DELAY = 1

# Enable AutoThrottle
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 1
AUTOTHROTTLE_MAX_DELAY = 10
AUTOTHROTTLE_TARGET_CONCURRENCY = 4

Getting Blocked / 403 Errors

Solution: Use residential proxies, rotate user agents, and add delays.

python
# settings.py

# Use residential proxies with country targeting
DATASEA_PROXY_USER = 'your_username_country-UnitedStates'

# Rotate User-Agent
# pip install scrapy-user-agents
DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
    'scrapy_user_agents.middlewares.RandomUserAgentMiddleware': 400,
    'myproject.middlewares.DataSeaProxyMiddleware': 350,
}

# Add random delays
DOWNLOAD_DELAY = 2
RANDOMIZE_DOWNLOAD_DELAY = True

# Respect robots.txt (some sites)
ROBOTSTXT_OBEY = False

Memory Issues on Large Crawls

Solution: Enable job persistence and optimize memory usage.

python
# settings.py

# Enable job persistence for resumable crawls
JOBDIR = 'crawls/myspider-1'

# Reduce memory usage
CONCURRENT_REQUESTS = 8
DEPTH_LIMIT = 3

# Disable unnecessary features
TELNETCONSOLE_ENABLED = False
MEMUSAGE_ENABLED = True
MEMUSAGE_LIMIT_MB = 512
MEMUSAGE_WARNING_MB = 256

# Close spider on memory limit
CLOSESPIDER_PAGECOUNT = 10000

Get started with industry‑leading proxy access

Connect to 150M+ real IPs in seconds. Built for scale, privacy, and performance. Free trial available.