Python Scrapy ile Entegrasyon

Python Scrapy crawler'larını, istekleri XProxy bağlantı noktaları üzerinden yönlendirecek şekilde yapılandırmayı ve istek eşiklerinde otomatik IP rotasyonunu yöneten özel bir middleware uygulamayı öğrenin.

Scrapy ile XProxy neden birlikte kullanılır?

Scrapy, yüksek performanslı veri toplama için tasarlanmış asenkron bir Python kazıma (scraping) çerçevesidir. Yüksek verimli kazıyıcılar çalıştırırken, kullanıma göre ücretlendirilen bulut proxy'leri kullanmak ciddi aylık maliyetlere yol açar. Scrapy'yi yerel SIM kartlarla kendi XProxy çiftliğiniz üzerinden çalıştırmak sınırsız veri hattı sağlar; dinamik operatör CGNAT IP'lerinden yararlanırken binlerce dolar tasarruf edersiniz.

XProxy proxy bağlantı noktaları listesi ve ayarları

Scrapy'de temel proxy yapılandırması

Scrapy'de XProxy kullanmanın en basit yolu, standart HttpProxyMiddleware bileşenini yapılandırıp proxy ayarlarını doğrudan settings.py dosyasına eklemek ya da istek bazında belirtmektir.

Seçenek A: settings.py içinde genel yapılandırma

Scrapy projenizin settings.py dosyasını açın ve aşağıdaki ayarları ekleyin:

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)

Seçenek B: Proxy'yi her Request için dinamik olarak geçirme

Ayrıca spider dosyanızın içinde, tek tek isteklere doğrudan bir proxy bağlantısı da atayabilirsiniz:

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}")

Gelişmiş: Otomatik IP rotasyonu middleware'i

Google bir CAPTCHA gösterdiğinde ya da belirli sayıda sayfa isteğinden sonra XProxy mobil IP'nizi otomatik olarak döndürmek için özel bir Scrapy middleware'i uygulayın:

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)}")

Middleware'i settings.py dosyanızda etkinleştirin:

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