Skip to content
Esc

Articles

What is a proxy? A plain-English guide for beginners: how it works, the types, and what it's forWhat is a 4G proxy? How mobile proxies work, pros, cons and when to use oneRotating proxies explained: rotation types and how to change a proxy IP with a linkSOCKS5 vs HTTP proxies: what's the difference and which should you use?Proxy vs VPN: what's the difference, and when should you use each?Static vs rotating proxies: how they differ, pros and cons, and when to use eachDedicated vs shared proxies: how they differ, and what "dedicated" means for a 4G proxyIPv4 vs IPv6 proxies: how they differ, why IPv6 proxies are cheap, and when they don't workHow do websites detect proxies? 8 signals anti-bot systems look atProxy glossary A to Z: 35 terms you'll meet when buying and using proxies, explained simplyProxy vs antidetect browser: how they differ, and do you need a proxy if you have antidetect?What is a residential proxy? How it works, pros and cons, and when to use oneWhat is a datacenter proxy? Pros and cons, why it's cheap, and when it's still the right choiceHow to find your IP address on a computer or phone: public IP, local IP, and your IP behind a proxyWhy do you keep getting CAPTCHAs? 9 common triggers, and where your IP fits inreCAPTCHA vs hCaptcha vs Cloudflare Turnstile: how each one decides who gets challengedWhat is botting? Good bots, bad bots, and where your own automation fitsHow to get a Singapore IP address: VPN, proxy, cloud server or SIM, and how to check itProxies for Facebook: managing several accounts more reliably with 4G IPsProxies for TikTok and TikTok Shop: when you need a Singapore IP and how to use it properlyProxies for advertising: checking and managing ads aimed at SingaporeProxies for e-commerce sellers: see marketplaces like a buyer, track competitors, keep store logins steadyProxies for web scraping: which type to choose, how to rotate, and how to play fairDo you need a proxy to buy tickets on ThaiTicketMajor, Ticketmelon or SISTIC?Scraping Google and Bing search results with a proxy, and when to use the API insteadHow to scrape without getting blocked: pace, sessions and clean IPsProxies for price monitoring: tracking competitor and retail prices across regionsScraping anti-bot and anti-proxy websites (Cloudflare, Akamai, DataDome): what works, and the limitsIs web scraping legal? Robots.txt, terms, personal data and copyright (Vietnam, Singapore and beyond)What are 4G proxies used for? 10 jobs mobile proxies do well, and the ones to avoid4G proxies for testing apps and websites as a Singapore mobile user: QA, ads, payments, bot rulesProxies for Instagram: managing brand and client accounts steadily with 4G IPsUsing a proxy to check flight and hotel prices as a Singapore user: when it helps and what to knowResearching the Singapore market with a proxy: see search, ads, marketplaces and competitors as a local userProxies for LinkedIn: managing B2B accounts and reaching the Singapore market the right wayProxies for X (Twitter): managing brand and client accounts steadily and within the rulesProxies for airdrops: why farming wallets through proxies gets disqualified, and how to join airdrops safelyProxies for seeding, bought likes and fake reviews: why they get caught, the risks, and lasting ways to growProxies for flash sales and limited drops: what a proxy can and can't do, and how to shop sales properlyProxies for large-scale, multi-country scraping: choosing proxy types, system design and real costsProxies for Netflix, YouTube and foreign streaming: why they usually fail, cost a lot, and what to do insteadSelling to Singapore from Vietnam: choosing channels, GST, shipping, payments and the tools you needSelling on TikTok Shop Singapore from abroad: seller requirements, workable routes and what a proxy can doThe Singapore online shopping market: who shops, where, how they pay and the big sale seasonsA workflow for agencies managing client accounts with proxies and antidetect: inventory, access, offboardingLocal SEO in Singapore: checking Google and Google Maps rankings as a Singapore user, the right wayProxies for Google Ads: when you need one, the official tools to use first, and the policy lines to knowRoblox lagging, high ping: does a proxy help, and the fixes that really reduce Roblox lagMultiple Roblox accounts (alts): what the rules allow and forbid, whether you need a proxy, and IP bansLag and high ping on Singapore game servers: do proxies or VPNs lower ping, and what actually helpsDiscord proxy: what it can and can't do, how to set it up, and managing communities the right wayShopee and Lazada Singapore proxies: see what Singapore buyers see, run your shop, track competitorsProxies for online business (MMO): which jobs need one, which type to pick and what to avoidProxy for bots and automation: one identity per IP, a polite pace, and what to do when a CAPTCHA appearsHow to set up a proxy on Windows, macOS, iPhone and Android (with a username and password)How to add a proxy to GoLogin, AdsPower, Hidemyacc, GenLogin and MultiloginRotate a proxy IP automatically with an API: curl, Python and Node.js examplesHow to check a proxy: IP, country, carrier, speed and DNS and WebRTC leaksCommon proxy errors and how to fix them: 407, timeouts, ERR_PROXY_CONNECTION_FAILEDScraping JavaScript-rendered sites with a headless browser and a proxy403, 429 and 503 errors when scraping: causes and how to handle them properly (with Python code)Using a proxy with Scrapy: authenticated setup, polite throttling, error fixes and rotating between runsUsing a proxy with curl and wget: HTTP, SOCKS5, authentication, environment variables and debuggingUsing a proxy in Python: requests, httpx and aiohttp with HTTP, SOCKS5 and authenticationSetting up a proxy in Chrome and Edge: a browser-only proxy without changing the whole computerSingapore proxy for Telegram: set up SOCKS5 on desktop, iPhone and Android, and how it differs from MTProtoSlow 4G proxy? How to measure speed and latency properly, and what really makes a proxy fasterUsing proxies safely: protect your proxy password, rotation link, accounts and dataUsing Proxifier for software without proxy support: SOCKS5 setup, per-app rules and DNSRoblox proxies for developers: calling Roblox APIs from HttpService, Open Cloud, and a safe self-hosted relayProtecting your Roblox account: cookie theft, "free Robux", malicious extensions, and how to stay safeHow to set up a proxy in AdsPower: HTTP or SOCKS5, where to paste it, checking the Singapore IP and rotatingHow to add a proxy to GoLogin: HTTP or SOCKS5, where to enter it, checking the Singapore IP and rotatingHow to add a proxy to GenLogin: HTTP or SOCKS5, where to paste it, checking the Singapore IP and rotatingHow to add a proxy to Hidemium: HTTP or SOCKS5, where to enter it, checking the Singapore IP and rotatingHow to add a proxy to BitBrowser: HTTP or SOCKS5, where to enter it, checking the Singapore IP and rotatingCAPTCHA keeps appearing or loops forever: 8 fixes, in the order to try themProxy keeps disconnecting? Why 4G proxies drop connections and how to handle itPlaywright proxy: set up an authenticated proxy in Python and Node.jsPuppeteer proxy: --proxy-server, page.authenticate and a proxy per browser contextUsing a proxy in Node.js: fetch, axios, got and SOCKS5 with a username and passwordMobile vs residential vs datacenter proxies: comparing 4G, home and server IPs, and how to chooseSingapore proxies: when you need a Singapore IP and which type to chooseClean proxies and blacklists: what a clean IP means, and why "never blocked" is a myth4G rotating proxies: how mobile IP rotation works, what clean rotation means and how to choose oneHow to tell a real 4G proxy from a fake: check the carrier, IP type, latency and rotationFree vs paid proxies: the real risks of free proxies, and when paying is worth itDedicated 4G proxies, not shared: why a proxy only you use matters, and how to check it yourselfHow many proxies do I need? Working out the number for accounts, teams and scrapingStatic IP proxies for allowlists, APIs and remote access: 5 options and how to choose the right oneVietnam or Singapore proxy? Choosing which country's IP fits your workSingtel, M1 and StarHub proxies: which Singapore carrier a 4G proxy runs on, and how to check itClean proxy and CAPTCHA: how IP reputation decides how many challenges you seeThe real cost of a dirty proxy: CAPTCHAs, retries, wasted bandwidth and blocked accountsSingapore SOCKS5 proxy: when to use it, how to set it up, and how to check it5G proxy vs 4G proxy: what changes, what doesn't, and whether 5G is worth paying more forCheap 4G proxies: $4 gets you 200GB, and how to compare mobile proxy prices properly before you buyRefer a friend and earn 10% on every proxy order: how the 65Proxy referral program worksWhy choose 65Proxy? 8 reasons you can verify, and when you should go elsewhereHow to buy a 4G proxy at 65Proxy: sign up, top up, pay, connect and rotate, step by stepWhere to buy a reliable proxy? 12 things to check before paying any providerTesting a 4G proxy in a 1-hour trial: a minute-by-minute checklistBuy proxies with USDT: paying for a Singapore 4G proxy over TRC20 or BEP20, step by step4G proxy with 500GB: what the plan includes, how far 500GB goes, and how bandwidth is countedGuides to 4G mobile proxies

Using a proxy with Scrapy: authenticated setup, polite throttling, error fixes and rotating between runs

Setup and use 7 min read

In this article
  1. 01 How Scrapy uses a proxy
  2. 02 Way 1: environment variables
  3. 03 Way 2: a Scrapy proxy middleware
  4. 04 Polite throttling
  5. 05 Check the proxy is in use
  6. 06 Rotating between runs
  7. 07 Common errors
  8. 08 65Proxy's Singapore 4G proxies for Scrapy
  9. 09 Frequently asked questions

Scrapy supports proxies out of the box: set request.meta["proxy"] (or the http_proxy and https_proxy environment variables) to http://USER:PASS@HOST:PORT and its built-in HttpProxyMiddleware handles the login. The documentation is just scattered, so this guide gathers what you need: two ways to add an authenticated proxy, including a complete proxy middleware, a "polite" throttling setup that lowers the chance of getting blocked, how to check the proxy is in use, the usual errors, and how to rotate a 4G proxy's IP without breaking a run.

How Scrapy uses a proxy

Scrapy ships with HttpProxyMiddleware, enabled by default. It takes the proxy from two places:

  • the environment variables http_proxy and https_proxy, read once when Scrapy starts,
  • each request's request.meta["proxy"], which takes priority over the environment.

The username and password go straight into the proxy address (http://USER:PASS@HOST:PORT). Scrapy splits them out and sends the proxy an authentication header.

Note: Scrapy only supports HTTP/HTTPS proxies, not SOCKS5. With 65Proxy, use the HTTP connection details. The difference between the two is in SOCKS5 vs HTTP proxies.

Way 1: environment variables

The quickest way, applying to every request. Both variables start with http://, even https_proxy, because Scrapy talks to the proxy over HTTP:

Terminal
export https_proxy="http://USER:PASS@HOST:PORT"
export http_proxy="$https_proxy"
scrapy crawl prices -O prices.json

On Windows PowerShell:

PowerShell
$env:HTTPS_PROXY = "http://USER:PASS@HOST:PORT"
$env:HTTP_PROXY  = $env:HTTPS_PROXY
scrapy crawl prices -O prices.json

Way 2: a Scrapy proxy middleware

When you want control in code (only some domains through the proxy, another proxy for a few requests, or a clear error when the proxy isn't set), write a small downloader middleware that sets request.meta["proxy"]. Scrapy's built-in HttpProxyMiddleware does the rest: it takes the username and password out of that URL and sends them to the proxy as a Proxy-Authorization header.

1. The middleware. In myproject/middlewares.py:

Python
import os
from urllib.parse import urlparse


class AuthProxyMiddleware:
    """Send requests through one HTTP proxy with a username and password."""

    def __init__(self, proxy_url, domains):
        self.proxy_url = proxy_url  # http://USER:PASS@HOST:PORT
        self.domains = domains      # empty list = every request

    @classmethod
    def from_crawler(cls, crawler):
        proxy_url = os.environ.get("PROXY_URL")
        if not proxy_url:
            # Stop here rather than crawl from your own IP by mistake.
            raise RuntimeError("Set PROXY_URL to http://USER:PASS@HOST:PORT")
        return cls(proxy_url, crawler.settings.getlist("PROXY_DOMAINS"))

    def process_request(self, request, spider=None):
        if "proxy" in request.meta:
            return None  # this request chose its own proxy
        host = urlparse(request.url).hostname or ""
        if self.domains and not any(
            host == d or host.endswith("." + d) for d in self.domains
        ):
            return None  # not a domain we send through the proxy
        request.meta["proxy"] = self.proxy_url
        return None

2. Enable it in settings.py. Downloader middlewares see each request in increasing order of their number, and HttpProxyMiddleware sits at 750, so give yours a lower number:

Python
DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.AuthProxyMiddleware": 740,
}
PROXY_DOMAINS = []  # e.g. ["example.sg"]; empty = proxy every request

Replace myproject with your project's name. Leave HttpProxyMiddleware enabled (don't set it to None): it's the part that turns USER:PASS in the URL into the authentication header.

3. Run it. Pass the proxy in an environment variable, so the username and password stay out of your code and settings:

Terminal
export PROXY_URL="http://USER:PASS@HOST:PORT"
scrapy crawl prices -O prices.json

On Windows PowerShell, set it with $env:PROXY_URL = "http://USER:PASS@HOST:PORT", then run the same scrapy crawl line. When the crawl starts, Scrapy's log lists the enabled downloader middlewares; AuthProxyMiddleware should be among them.

Details worth knowing:

  • Special characters in the password must be percent-encoded in PROXY_URL (@ becomes %40, : becomes %3A). Scrapy decodes them before sending.
  • One request through a different proxy: set it on that request, for example scrapy.Request(url, meta={"proxy": "http://USER2:PASS2@HOST2:PORT2"}). The middleware leaves requests that already have meta["proxy"] alone.
  • Don't mix both ways. meta["proxy"] takes priority over http_proxy and https_proxy, but requests the middleware skips would still use the environment proxy if you also exported it as in Way 1.
  • Changing the IP is done with the proxy's rotation link, outside the crawl: see rotating between runs.

Polite throttling

With a 4G proxy, every request goes out from one IP, so pace matters more than ever. A sensible starting point for settings.py:

Python
ROBOTSTXT_OBEY = True
USER_AGENT = "my-crawler/1.0 (+mailto:[email protected])"

CONCURRENT_REQUESTS_PER_DOMAIN = 2
DOWNLOAD_DELAY = 2              # seconds; Scrapy varies it 0.5–1.5x
DOWNLOAD_TIMEOUT = 30           # the 180-second default is too long

AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 2
AUTOTHROTTLE_MAX_DELAY = 60
AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0

RETRY_TIMES = 3
RETRY_HTTP_CODES = [500, 502, 503, 504, 522, 524, 408, 429]

HTTPCACHE_ENABLED = True        # while developing: don't re-download pages
  • AutoThrottle slows down automatically when the site responds slowly.
  • The default retry middleware doesn't wait per Retry-After. If you see 429s often, raise DOWNLOAD_DELAY and lower CONCURRENT_REQUESTS_PER_DOMAIN rather than adding retries. What each error code means is in 403, 429 and 503 errors when scraping.
  • The HTTP cache while developing lets you fix your parsing code without hitting the target again. Turn it off for real runs if you need fresh data.

Check the proxy is in use

scrapy fetch downloads a page with the current settings and prints it:

Terminal
scrapy fetch --nolog https://api.ipify.org

The result should be the proxy's IP, not your home IP. To see the network and country as well:

Terminal
scrapy fetch --nolog https://ipinfo.io/json

Rotating between runs

With a 4G proxy, rotating means calling the proxy's rotation link and waiting for the device to reconnect. In Scrapy, the cleanest approach is to rotate between runs, not between requests:

  • rotating mid-run leaves cookies and sessions out of step with the IP,
  • in-flight requests fail while the device reconnects,
  • and each 65Proxy proxy rotates at most once every 5 minutes.

A script to run before each crawl (the rotation link lives in the ROTATE_URL environment variable):

Terminal
export https_proxy="http://USER:PASS@HOST:PORT"
export http_proxy="$https_proxy"

old=$(curl -s -m 15 -x "$https_proxy" https://api.ipify.org)
curl -s -m 60 "$ROTATE_URL" > /dev/null
for i in $(seq 1 20); do
  sleep 3
  new=$(curl -s -m 10 -x "$https_proxy" https://api.ipify.org)
  if [ -n "$new" ] && [ "$new" != "$old" ]; then break; fi
done
echo "IP: $old -> $new"

scrapy crawl prices -O prices.json

The same in Python, which also runs on Windows and works with the middleware above: it rotates, waits for the new IP, then starts the crawl. Save it as run_crawl.py next to scrapy.cfg and run python run_crawl.py with PROXY_URL and ROTATE_URL set:

Python
import os
import time
import urllib.request

from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

PROXY_URL = os.environ["PROXY_URL"]    # http://USER:PASS@HOST:PORT
ROTATE_URL = os.environ["ROTATE_URL"]  # the proxy's rotation link

# Call the rotation link directly; check the IP through the proxy.
direct = urllib.request.build_opener(urllib.request.ProxyHandler({}))
via_proxy = urllib.request.build_opener(
    urllib.request.ProxyHandler({"http": PROXY_URL, "https": PROXY_URL})
)


def proxy_ip():
    try:
        return via_proxy.open("https://api.ipify.org", timeout=15).read().decode()
    except OSError:
        return None  # the device is still reconnecting


old_ip = proxy_ip()
try:
    direct.open(ROTATE_URL, timeout=60).read()
except OSError as err:
    raise SystemExit(f"Rotation failed: {err}")
for _ in range(20):
    time.sleep(3)
    new_ip = proxy_ip()
    if new_ip and new_ip != old_ip:
        break
else:
    raise SystemExit("The IP did not change. Was the last rotation under 5 minutes ago?")
print(f"IP: {old_ip} -> {new_ip}")

settings = get_project_settings()
settings.set("FEEDS", {"prices.json": {"format": "json", "overwrite": True}})
process = CrawlerProcess(settings)
process.crawl("prices")
process.start()

The rotation link is called without the proxy, so the call doesn't depend on the connection it's about to reset. More versions of the wait loop (curl, Python, Node.js) are in rotating proxy IPs via API.

Common errors

  • 407 Proxy Authentication Required: wrong username or password. If the password has special characters, encode them in the proxy address: @ becomes %40, : becomes %3A.
  • TunnelError: Could not open CONNECT tunnel. The proxy refused to open a tunnel for HTTPS; usually wrong credentials, the wrong port, or a SOCKS5 port by mistake.
  • Errors with socks5://: Scrapy doesn't support SOCKS; switch to the HTTP port.
  • A burst of timeouts: usually while the proxy is rotating or signal is weak; sensible RETRY_TIMES and DOWNLOAD_TIMEOUT handle it.
  • The IP is still your home IP: the environment variable was set after Scrapy started, or in a different terminal window.

General proxy errors are covered in common proxy errors.

65Proxy's Singapore 4G proxies for Scrapy

Our proxies have an HTTP port with a username and password (exactly what Scrapy needs) plus an on-demand rotation link (at most once every 5 minutes). Singapore mobile-carrier IPs help you reach public data on sites that block server IPs, or data shown only to Singapore visitors. Priced 1 day $4, 7 days $13, 1 month $32 (200GB each), plus monthly plans with more bandwidth (500GB $40, 1TB $65). Use them with the throttling setup above and respect each site's rules. See is web scraping legal and pricing.

Frequently asked questions

Is one 4G proxy enough for Scrapy?

For polite scraping (a few requests a second or fewer per site), it usually is. If you need much more speed, ask the target site about an API before thinking about more IPs.

Is there a rotating-proxy middleware for Scrapy?

There are libraries that cycle through a list of proxies. With a 4G proxy that rotates by link you don't need them. Just rotate between runs as above.

Can Scrapy run JavaScript?

Scrapy itself can't. For pages that need JavaScript, look for the API the page calls, or use a headless browser. See scraping JavaScript sites.