Scrapy와 XProxy 연동

Python Scrapy 크롤러가 XProxy 포트를 통해 요청을 라우팅하도록 구성하고, 특정 요청 지점에서 자동 IP 로테이션을 처리하는 커스텀 미들웨어를 구현하는 방법을 배웁니다.

Scrapy와 함께 XProxy를 사용하는 이유

Scrapy는 고성능 데이터 크롤링을 위해 설계된 비동기 Python 스크래핑 프레임워크입니다. 고처리량 스크레이퍼를 실행할 때 유료 클라우드 프록시를 사용하면 월 비용이 엄청나게 발생합니다. 로컬 SIM 카드를 사용하는 자체 XProxy 팜으로 Scrapy를 실행하면 무제한 데이터 파이프라인을 확보해 수천 달러를 절약하면서 동적 통신사 CGNAT IP를 활용할 수 있습니다.

XProxy 프록시 포트 목록 및 설정

Scrapy 기본 프록시 구성

Scrapy에서 XProxy를 사용하는 가장 간단한 방법은 표준 HttpProxyMiddleware를 활성화하고 settings.py에 프록시 설정을 추가하거나 요청별로 지정하는 것입니다.

옵션 A: settings.py에서 전역 구성

Scrapy 프로젝트의 settings.py를 열고 다음 설정을 추가합니다:

settings.py
# Enable the default HTTP Proxy Middleware
DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 400,
}

# Define your XProxy SOCKS5 or HTTP proxy URL
# Replace 192.168.6.7:5001 with your XProxy server IP and port
HTTP_PROXY = 'http://your_username:[email protected]:5001'

# Set proxy to environment variable (or configure in custom middleware)

옵션 B: 요청별로 프록시를 동적으로 전달

스파이더 파일에서 개별 요청에 프록시 연결을 직접 할당할 수도 있습니다:

myspider.py
import scrapy

class MySpider(scrapy.Spider):
    name = 'myspider'

    def start_requests(self):
        urls = ['https://httpbin.org/ip']
        for url in urls:
            yield scrapy.Request(
                url=url,
                callback=self.parse,
                meta={
                    # Route this specific request through XProxy port 5001
                    'proxy': 'http://your_username:[email protected]:5001'
                }
            )

    def parse(self, response):
        self.logger.info(f"Response: {response.text}")

고급: 자동 IP 로테이션 미들웨어

Google이 CAPTCHA를 표시하거나 특정 페이지 요청 수 이후 XProxy 모바일 IP를 자동으로 로테이션하려면 커스텀 Scrapy 미들웨어를 구현합니다:

middlewares.py
import time
import requests
from scrapy.exceptions import NotConfigured

class XProxyRotationMiddleware:
    def __init__(self, rotate_url, request_limit=100):
        self.rotate_url = rotate_url
        self.request_limit = request_limit
        self.request_count = 0

    @classmethod
    def from_crawler(cls, crawler):
        # Read settings from settings.py
        rotate_url = crawler.settings.get('XPROXY_ROTATE_URL')
        request_limit = crawler.settings.getint('XPROXY_REQUEST_LIMIT', 100)
        
        if not rotate_url:
            raise NotConfigured
            
        return cls(rotate_url, request_limit)

    def process_request(self, request, spider):
        self.request_count += 1
        
        # Trigger rotation if limit reached
        if self.request_count >= self.request_limit:
            spider.logger.info("Request limit reached. Triggering XProxy IP rotation...")
            self._trigger_rotation(spider)
            self.request_count = 0
            
    def _trigger_rotation(self, spider):
        try:
            response = requests.get(self.rotate_url)
            spider.logger.info(f"IP rotation triggered: {response.status_code} - {response.text}")
            # Wait for 6 seconds for cellular reconnection
            time.sleep(6)
        except Exception as e:
            spider.logger.error(f"Failed to trigger rotation: {str(e)}")

settings.py에서 미들웨어를 활성화합니다:

settings.py
DOWNLOADER_MIDDLEWARES = {
    'myproject.middlewares.XProxyRotationMiddleware': 350,
    'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 400,
}

# The XProxy Rotation API URL for your device position
XPROXY_ROTATE_URL = 'http://192.168.6.7:8081/api/v1/rotate_ip/position/1'
# Rotate the IP address after every 150 requests
XPROXY_REQUEST_LIMIT = 150

Why High-Quality SOCKS5 UDP & Mobile Proxies Matter for Python Scrapy Crawlers

Using cheap datacenter proxies or basic HTTP proxies in antidetect profiles leads to instant account suspensions on Facebook, Google, TikTok, and Amazon. Here is why XProxy's self-hosted 4G/5G mobile proxies deliver superior anonymity and trust:

  • SOCKS5 with Full UDP Support: Unlike standard HTTP proxies that drop UDP packets, XProxy SOCKS5 proxies fully support UDP datagrams. This ensures WebRTC, DNS queries, and real-time audio/video sockets route securely through your proxy without revealing your real IP address.
  • Instant REST API IP Rotation: Trigger cellular IP rotation on demand via simple HTTP GET requests (e.g. http://192.168.6.7:8081/api/v1/rotate_ip/position/1). Reconnect 4G/5G USB modems in 3 to 8 seconds with zero proxy dropouts.
  • 100% WebRTC & DNS Leak Protection: Combined with XProxy's local LAN gateway and TCP OS Spoofing, your browser profiles maintain pristine anonymity scores on BrowserLeaks, Whoer, Pixelscan, and IPhey.
  • Carrier-Grade NAT (CGNAT) Trust: Mobile carrier IPs are shared by thousands of active smartphone users. Major platforms never ban mobile IP ranges, granting your accounts maximum trust.
🚀 Build Your Own 4G/5G Proxy Farm

Stop Paying Monthly Rented Proxy Fees

XProxy hardware & software lets you own private mobile proxy channels with unlimited data, zero bandwidth caps, SOCKS5 UDP support, and instant REST API IP rotation (Scrapy Crawlers).

XProxy XH22 4G 5G Mobile Proxy Hardware Kit