Integração com Python Scrapy
Aprenda a configurar os crawlers Python Scrapy para rotear as requisições pelas portas do XProxy e a implementar um middleware personalizado para gerenciar a rotação automática de IP em marcos de requisição.
Por que usar o Scrapy com o XProxy?
O Scrapy é um framework de scraping em Python, assíncrono, projetado para coleta de dados de alto desempenho. Ao executar scrapers de alta vazão, o uso de proxies de nuvem com cobrança por uso gera custos mensais enormes. Executar o Scrapy por meio do seu próprio farm XProxy com cartões SIM locais oferece pipelines de dados ilimitados, fazendo você economizar milhares de dólares enquanto aproveita os IPs CGNAT dinâmicos da operadora.

Configuração básica de proxy no Scrapy
A maneira mais simples de usar o XProxy no Scrapy é configurando o HttpProxyMiddleware padrão e adicionando as configurações de proxy diretamente no settings.py ou especificando-as por requisição.
Opção A: Configuração global no settings.py
Abra o settings.py do seu projeto Scrapy e adicione as seguintes configurações:
# 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)Opção B: Passar o proxy dinamicamente por Request
Você também pode atribuir uma conexão de proxy diretamente no arquivo do seu spider a requisições individuais:
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}")Avançado: Middleware de rotação automática de IP
Para rotacionar automaticamente o IP móvel do XProxy quando o Google apresentar um CAPTCHA, ou após um número específico de requisições de página, implemente um middleware personalizado do Scrapy:
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)}")Ative o middleware no seu 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 = 150Why 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.
