수백 개의 요청을 처리할 때 수동으로 프록시를 변경하는 것은 시간과 비용 낭비입니다. API 로테이션을 사용하면 차단 시 IP 주소를 자동으로 전환하고, 부하를 분산하며, 파싱이나 멀티 어카운팅을 확장할 수 있습니다. 이 가이드에서는 마켓플레이스 파싱부터 Facebook Ads 계정 파밍까지 다양한 작업을 위한 프록시 자동 교체 설정 방법을 살펴보겠습니다.
이 자료는 Python이나 Node.js로 파서를 작성하는 개발자와 API 통합 기능이 있는 기성 도구를 사용하는 중재자 모두에게 적합합니다.
API를 통한 프록시 자동 교체가 필요한 이유
API를 통한 IP 주소 자동 로테이션은 다양한 분야의 전문가들이 직면하는 몇 가지 중요한 과제를 해결합니다:
마켓플레이스 및 웹사이트 파싱: Wildberries, Ozon 또는 Avito에서 데이터를 수집할 때 각 IP는 제한된 수의 요청(일반적으로 시간당 50-200개)만 할 수 있습니다. API 로테이션을 사용하면 한도에 도달하거나 캡차를 받을 때 자동으로 새 IP로 전환하여 지속적인 데이터 수집을 보장합니다.
중재 및 멀티 어카운팅: 20-50개의 Facebook Ads 광고 계정이나 Instagram 계정으로 작업할 때 각 프로필을 격리해야 합니다. API를 사용하면 Dolphin Anty나 AdsPower의 각 계정에 고유한 프록시를 프로그래밍 방식으로 할당하고 차단 시 세션을 자동으로 재생성할 수 있습니다.
SMM 자동화: Instagram, TikTok 또는 VK에 대량 게시하는 서비스는 속도 제한을 피하기 위해 IP 주소 간에 작업을 분산해야 합니다. API를 사용하면 각 세션이나 계정 그룹에 대해 동적으로 새 프록시를 얻을 수 있습니다.
수동 교체와 비교한 API 자동화의 주요 장점:
- 속도: IP 교체가 사람의 개입 없이 프로그래밍 방식으로 밀리초 단위로 발생합니다
- 확장성: 단일 인터페이스를 통해 수천 개의 프록시를 동시에 관리할 수 있습니다
- 내결함성: 프로세스를 중단하지 않고 작동하지 않는 프록시를 자동으로 교체합니다
- 유연성: 특정 작업에 맞게 로테이션 규칙 설정: 시간별, 요청 수별, 지역별
- 비용 절감: 부하 분산을 통한 트래픽의 최적 사용
일반적인 사용 시나리오: Wildberries에서 경쟁사 가격을 파싱합니다. API가 없으면 차단을 수동으로 추적하고, 프록시 제공업체 패널에 로그인하고, 새 데이터를 복사하여 스크립트에 붙여넣어야 합니다. API를 사용하면 이 모든 것이 자동으로 발생합니다: 스크립트가 429 오류(Too Many Requests)를 받으면 프록시 서비스 API에 요청을 보내고 새 IP를 받아 작업을 계속합니다.
프록시 로테이션 유형: 고정 세션 vs 자동 교체
자동화를 설정하기 전에 IP 주소 로테이션 유형 간의 차이를 이해하는 것이 중요합니다. 전략 선택은 작업에 따라 다릅니다.
고정 세션(Sticky Sessions)
고정 세션을 사용하면 하나의 IP 주소가 특정 시간(일반적으로 5~30분) 동안 세션에 고정됩니다. 교체는 세션 시간이 만료되거나 API 요청이 있을 때만 발생합니다.
사용 시기:
- 소셜 네트워크(Instagram, Facebook) 계정 작업 - 잦은 IP 변경은 의심을 불러일으킵니다
- 세션을 유지해야 하는 다중 페이지 양식 작성
- 세션 중 특정 지역에서 광고 테스트
- IP 변경으로 인해 로그아웃되는 인증이 있는 사이트 파싱
고정 세션 생성을 위한 API 요청 예제(일반적으로 특수 로그인 형식 사용):
// 형식: username-session-SESSIONID:password
// SESSIONID — 임의의 문자열, 동일하면 = 하나의 IP
proxy = "username-session-abc123:password@gate.proxycove.com:8000"
// session-abc123이 있는 모든 요청은 세션 기간 동안 하나의 IP를 받습니다
// 새 IP를 위해 다른 SESSIONID 사용: session-xyz789
요청마다 자동 로테이션
IP 주소는 프록시 서버에 새로 연결할 때마다 변경됩니다. 이것은 세션 매개변수를 지정하지 않은 주거용 프록시의 표준 동작입니다.
사용 시기:
- 인증 없는 대량 파싱(가격, 연락처, 광고)
- 공개 API의 공격적인 속도 제한 우회
- 10-20개 요청 후 IP를 차단하는 사이트에서 데이터 수집
- 다양한 지역에서 콘텐츠 가용성 확인
Python 사용 예제(각 요청 = 새 IP):
import requests
proxy = {
"http": "http://username:password@gate.proxycove.com:8000",
"https": "http://username:password@gate.proxycove.com:8000"
}
# 각 요청은 새 IP를 받습니다
for i in range(10):
response = requests.get("https://api.ipify.org", proxies=proxy)
print(f"요청 {i+1}, IP: {response.text}")
타이머 기반 로테이션
IP를 언제 변경할지 프로그래밍 방식으로 제어합니다: N분마다, M개 요청 후 또는 특정 오류를 받을 때. 이것은 프록시 서비스 API를 통해 구현되는 하이브리드 접근 방식입니다.
사용 시기:
- 트래픽 사용 최적화 - 필요할 때만 교체
- 패턴을 추적하는 사이트 작업(너무 잦은 교체 = 차단)
- 익명성과 세션 안정성 간의 균형
| 로테이션 유형 | IP 교체 빈도 | 작업 | 트래픽 사용량 |
|---|---|---|---|
| 고정 세션 | 5-30분 | 멀티 어카운팅, 인증 | 낮음 |
| 자동 로테이션 | 매 요청 | 파싱, 속도 제한 우회 | 중간 |
| 타이머 기반 | 설정 가능 | 범용 | 최적화됨 |
프록시 서비스 API 작업 기초
대부분의 최신 프록시 제공업체는 웹 패널과 API를 통한 두 가지 관리 방법을 제공합니다. API는 프록시 목록 가져오기, 새 세션 생성, 잔액 확인, 사용 통계 등의 기능에 대한 프로그래밍 방식 액세스를 제공합니다.
프록시 서비스의 일반적인 API 메서드
각 제공업체마다 고유한 문서가 있지만 표준 메서드에는 일반적으로 다음이 포함됩니다:
- GET /api/v1/proxy/list — 국가, 유형별 필터링으로 사용 가능한 프록시 목록 가져오기
- POST /api/v1/proxy/rotate — 활성 세션에서 IP 강제 변경
- GET /api/v1/account/balance — 잔여 트래픽 또는 잔액 확인
- GET /api/v1/stats — 사용 통계: 트래픽 양, 요청 수, 오류
- POST /api/v1/session/create — 매개변수(국가, 도시, 기간)로 새 고정 세션 생성
인증은 일반적으로 요청 헤더의 API 키를 통해 이루어집니다:
curl -X GET "https://api.provider.com/v1/proxy/list?country=US" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"
응답은 일반적으로 JSON 형식으로 제공됩니다:
{
"status": "success",
"data": {
"proxies": [
{
"ip": "123.45.67.89",
"port": 8000,
"country": "US",
"city": "New York",
"protocol": "http",
"username": "user123",
"password": "pass456"
}
],
"total": 150,
"available": 147
}
}
API를 통한 세션 관리
IP 수명 제어가 필요한 작업(멀티 어카운팅, 계정 작업)의 경우 API를 통해 명명된 세션을 생성합니다. 이를 통해 수십, 수백 개의 격리된 IP 주소를 프로그래밍 방식으로 관리할 수 있습니다.
매개변수를 사용한 세션 생성 예제:
POST /api/v1/session/create
{
"country": "US",
"state": "California",
"session_duration": 600, // 10분
"session_id": "facebook_account_001"
}
// 응답:
{
"status": "success",
"session": {
"id": "facebook_account_001",
"proxy": "gate.provider.com:8000",
"username": "user-session-facebook_account_001",
"password": "your_password",
"ip": "45.67.89.123",
"expires_at": "2024-01-15T15:30:00Z"
}
}
이제 스크립트나 안티디텍트 브라우저에서 이 프록시를 사용할 수 있으며 IP는 10분 동안 변경되지 않습니다. 세션을 연장하려면 동일한 session_id로 반복 요청을 보냅니다.
Python 자동화 예제: requests, Selenium, Scrapy
Python은 파싱 및 자동화에 가장 인기 있는 언어입니다. 주요 도구와 API 로테이션 프록시 통합 예제를 살펴보겠습니다.
requests에서 프록시 자동 교체
requests 라이브러리는 간단한 HTTP 요청에 사용됩니다. 자동 로테이션을 위해 오류 시 프록시를 변경하는 래퍼 클래스를 만들어 보겠습니다:
import requests
import random
import time
class RotatingProxySession:
def __init__(self, proxy_list):
"""
proxy_list: 프록시 데이터가 있는 딕셔너리 목록
[{"http": "http://user:pass@ip:port", "https": "..."}]
"""
self.proxy_list = proxy_list
self.current_proxy = None
self.session = requests.Session()
self.rotate()
def rotate(self):
"""목록에서 무작위 프록시 선택"""
self.current_proxy = random.choice(self.proxy_list)
self.session.proxies.update(self.current_proxy)
print(f"프록시로 전환: {self.current_proxy['http']}")
def get(self, url, max_retries=3, **kwargs):
"""오류 시 자동 로테이션이 있는 GET 요청"""
for attempt in range(max_retries):
try:
response = self.session.get(url, timeout=10, **kwargs)
# 차단을 받으면 — 프록시 변경
if response.status_code in [403, 429, 503]:
print(f"{response.status_code} 받음, 프록시 변경 중...")
self.rotate()
time.sleep(2)
continue
return response
except requests.exceptions.ProxyError:
print(f"프록시가 작동하지 않음, 시도 {attempt+1}/{max_retries}")
self.rotate()
time.sleep(2)
except requests.exceptions.Timeout:
print("타임아웃, 프록시 변경 중...")
self.rotate()
time.sleep(2)
raise Exception(f"{max_retries}번 시도 후 요청 실패")
# 사용법:
proxies = [
{"http": "http://user1:pass@gate1.com:8000", "https": "http://user1:pass@gate1.com:8000"},
{"http": "http://user2:pass@gate2.com:8000", "https": "http://user2:pass@gate2.com:8000"},
]
session = RotatingProxySession(proxies)
# Wildberries 파싱
for page in range(1, 50):
url = f"https://www.wildberries.ru/catalog/page={page}"
response = session.get(url)
print(f"페이지 {page}: {response.status_code}")
브라우저 자동화를 위한 Selenium 통합
Selenium은 JavaScript가 있는 사이트 파싱 및 브라우저에서 작업 자동화에 사용됩니다. 프록시를 변경하려면 초기화 시 프록시 설정이 지정되므로 드라이버를 다시 만들어야 합니다:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
class SeleniumRotatingProxy:
def __init__(self, proxy_list):
self.proxy_list = proxy_list
self.driver = None
self.current_proxy_index = 0
def create_driver(self):
"""현재 프록시로 새 드라이버 생성"""
if self.driver:
self.driver.quit()
proxy = self.proxy_list[self.current_proxy_index]
chrome_options = Options()
chrome_options.add_argument(f'--proxy-server={proxy}')
chrome_options.add_argument('--headless') # GUI 없이
self.driver = webdriver.Chrome(options=chrome_options)
print(f"프록시로 드라이버 생성: {proxy}")
def rotate(self):
"""다음 프록시로 전환"""
self.current_proxy_index = (self.current_proxy_index + 1) % len(self.proxy_list)
self.create_driver()
def get_with_retry(self, url, max_retries=3):
"""오류 시 프록시 자동 변경으로 URL 열기"""
for attempt in range(max_retries):
try:
if not self.driver:
self.create_driver()
self.driver.get(url)
# 차단 확인(예: 캡차 검색)
if "captcha" in self.driver.page_source.lower():
print("캡차 감지, 프록시 변경 중...")
self.rotate()
time.sleep(3)
continue
return self.driver.page_source
except Exception as e:
print(f"오류: {e}, 프록시 변경 중(시도 {attempt+1})")
self.rotate()
time.sleep(3)
raise Exception("페이지 로드 실패")
# 사용법:
proxies = [
"http://user:pass@gate1.com:8000",
"http://user:pass@gate2.com:8000",
]
bot = SeleniumRotatingProxy(proxies)
# Ozon 파싱
for i in range(10):
html = bot.get_with_retry(f"https://www.ozon.ru/category/page-{i}")
print(f"페이지 {i} HTML 받음, 길이: {len(html)}")
bot.driver.quit()
프록시 로테이션을 위한 미들웨어가 있는 Scrapy
Scrapy는 대규모 파싱을 위한 프레임워크입니다. 프록시 로테이션은 모든 요청에 자동으로 적용되는 미들웨어를 통해 구현됩니다:
# middlewares.py
import random
from scrapy.exceptions import IgnoreRequest
class RotatingProxyMiddleware:
def __init__(self, proxy_list):
self.proxy_list = proxy_list
@classmethod
def from_crawler(cls, crawler):
# 설정에서 프록시 목록 가져오기
proxy_list = crawler.settings.getlist('ROTATING_PROXY_LIST')
return cls(proxy_list)
def process_request(self, request, spider):
# 각 요청에 무작위 프록시 할당
proxy = random.choice(self.proxy_list)
request.meta['proxy'] = proxy
spider.logger.info(f'프록시 사용: {proxy}')
def process_exception(self, request, exception, spider):
# 프록시 오류 시 — 다른 것으로 재시도
proxy = random.choice(self.proxy_list)
spider.logger.warning(f'프록시 오류, 전환 중: {proxy}')
request.meta['proxy'] = proxy
return request # 요청 재시도
# settings.py
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.RotatingProxyMiddleware': 350,
}
ROTATING_PROXY_LIST = [
'http://user:pass@gate1.com:8000',
'http://user:pass@gate2.com:8000',
'http://user:pass@gate3.com:8000',
]
# 오류 시 요청 재시도
RETRY_TIMES = 5
RETRY_HTTP_CODES = [403, 429, 500, 502, 503]
이제 각 Scrapy 요청은 목록에서 무작위 프록시를 자동으로 받으며 오류 시 다른 IP로 재시도됩니다.
Node.js 자동화: axios, Puppeteer, Playwright
Node.js는 비동기성과 브라우저 도구와의 우수한 통합 덕분에 파서 및 봇 생성에 인기가 있습니다. 주요 라이브러리에서 프록시 로테이션 예제를 살펴보겠습니다.
자동 로테이션이 있는 Axios
Axios는 HTTP 요청을 위한 라이브러리입니다. 프록시 풀과 오류 시 자동 교체 기능이 있는 클래스를 만들어 보겠습니다:
const axios = require('axios');
const HttpsProxyAgent = require('https-proxy-agent');
class RotatingProxyClient {
constructor(proxyList) {
this.proxyList = proxyList;
this.currentIndex = 0;
}
getProxy() {
const proxy = this.proxyList[this.currentIndex];
this.currentIndex = (this.currentIndex + 1) % this.proxyList.length;
return proxy;
}
async request(url, options = {}, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const proxy = this.getProxy();
const agent = new HttpsProxyAgent(proxy);
try {
const response = await axios.get(url, {
...options,
httpsAgent: agent,
timeout: 10000
});
// 차단을 받으면 — 다음 시도
if ([403, 429, 503].includes(response.status)) {
console.log(`상태 ${response.status}, 프록시 변경 중...`);
continue;
}
return response.data;
} catch (error) {
console.log(`프록시 ${proxy} 오류: ${error.message}`);
if (i === maxRetries - 1) throw error;
}
}
}
}
// 사용법:
const proxies = [
'http://user:pass@gate1.com:8000',
'http://user:pass@gate2.com:8000',
];
const client = new RotatingProxyClient(proxies);
(async () => {
for (let page = 1; page <= 20; page++) {
const data = await client.request(`https://api.example.com/products?page=${page}`);
console.log(`페이지 ${page}: ${data.length}개 제품 받음`);
}
})();
프록시 로테이션이 있는 Puppeteer
Puppeteer는 Chrome 브라우저를 제어합니다. 프록시는 브라우저 시작 시 설정되므로 변경하려면 인스턴스를 다시 만들어야 합니다:
const puppeteer = require('puppeteer');
class PuppeteerRotatingProxy {
constructor(proxyList) {
this.proxyList = proxyList;
this.currentIndex = 0;
this.browser = null;
}
async createBrowser() {
if (this.browser) await this.browser.close();
const proxy = this.proxyList[this.currentIndex];
console.log(`프록시로 브라우저 시작: ${proxy}`);
this.browser = await puppeteer.launch({
headless: true,
args: [`--proxy-server=${proxy}`]
});
}
rotate() {
this.currentIndex = (this.currentIndex + 1) % this.proxyList.length;
}
async scrape(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
if (!this.browser) await this.createBrowser();
const page = await this.browser.newPage();
// 프록시 인증(필요한 경우)
await page.authenticate({
username: 'your_username',
password: 'your_password'
});
await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 });
// 캡차 확인
const content = await page.content();
if (content.includes('captcha')) {
console.log('캡차 감지, 프록시 변경 중...');
this.rotate();
await this.createBrowser();
continue;
}
return content;
} catch (error) {
console.log(`오류: ${error.message}, 시도 ${i+1}`);
this.rotate();
await this.createBrowser();
}
}
throw new Error('페이지 로드 실패');
}
}
// 사용법:
const proxies = ['gate1.com:8000', 'gate2.com:8000'];
const scraper = new PuppeteerRotatingProxy(proxies);
(async () => {
const html = await scraper.scrape('https://www.avito.ru/moskva');
console.log(`HTML 길이 받음: ${html.length}`);
await scraper.browser.close();
})();
로테이션 지원이 있는 Playwright
Playwright는 더 나은 성능을 가진 Puppeteer의 현대적인 대안입니다. 프록시 설정은 유사합니다:
const { chromium } = require('playwright');
async function scrapeWithRotation(urls, proxyList) {
let proxyIndex = 0;
for (const url of urls) {
const proxy = proxyList[proxyIndex];
const browser = await chromium.launch({
headless: true,
proxy: {
server: proxy,
username: 'your_user',
password: 'your_pass'
}
});
const page = await browser.newPage();
try {
await page.goto(url, { timeout: 30000 });
const title = await page.title();
console.log(`${url} → ${title} (프록시: ${proxy})`);
} catch (error) {
console.log(`${url} 오류: ${error.message}`);
}
await browser.close();
// 다음 URL을 위한 다음 프록시
proxyIndex = (proxyIndex + 1) % proxyList.length;
}
}
const urls = [
'https://www.wildberries.ru',
'https://www.ozon.ru',
'https://www.avito.ru'
];
const proxies = [
'http://gate1.com:8000',
'http://gate2.com:8000'
];
scrapeWithRotation(urls, proxies);
안티디텍트 브라우저와 API 통합: Dolphin Anty, AdsPower
멀티 어카운팅으로 작업하는 중재자 및 SMM 전문가의 경우 Dolphin Anty 또는 AdsPower의 각 프로필에 프록시를 수동으로 할당하는 데 몇 시간이 걸립니다. 이러한 브라우저의 API를 사용하면 프로필 생성 및 프록시 바인딩을 자동화할 수 있습니다.
API를 통한 Dolphin Anty 자동화
Dolphin Anty는 로컬 API(일반적으로 http://localhost:3001/v1.0)를 제공하여 프로필 생성, 프록시 할당, 브라우저를 프로그래밍 방식으로 시작할 수 있습니다.
고유한 프록시로 프로필을 대량 생성하기 위한 Python 스크립트 예제:
import requests
import json
DOLPHIN_API = "http://localhost:3001/v1.0"
API_TOKEN = "your_dolphin_api_token"
# 프록시 제공업체의 프록시 목록(API를 통해 받음)
proxies = [
{"host": "gate1.com", "port": 8000, "login": "user1", "password": "pass1"},
{"host": "gate2.com", "port": 8000, "login": "user2", "password": "pass2"},
]
def create_profile_with_proxy(name, proxy):
"""프록시 바인딩으로 Dolphin에 프로필 생성"""
payload = {
"name": name,
"tags": ["Facebook Ads", "Auto-created"],
"proxy": {
"type": "http", # 또는 socks5
"host": proxy["host"],
"port": proxy["port"],
"login": proxy["login"],
"password": proxy["password"]
},
"fingerprint": {
"os": "win",
"webRTC": {
"mode": "altered",
"fillBasedOnIp": True
},
"canvas": {
"mode": "noise"
}
}
}
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
response = requests.post(
f"{DOLPHIN_API}/browser_profiles",
headers=headers,
data=json.dumps(payload)
)
if response.status_code == 200:
profile = response.json()
print(f"✓ 프로필 생성: {name}, ID: {profile['id']}")
return profile['id']
else:
print(f"✗ {name} 생성 오류: {response.text}")
return None
# 프록시 로테이션으로 50개 프로필 생성
for i in range(50):
proxy = proxies[i % len(proxies)] # 순환 로테이션
profile_name = f"FB_Account_{i+1:03d}"
create_profile_with_proxy(profile_name, proxy)
이제 Dolphin Anty에 각각 고유한 브라우저 지문과 프록시가 있는 50개의 프로필이 있습니다. 프로필을 프로그래밍 방식으로 시작하려면:
def start_profile(profile_id):
"""브라우저 프로필 시작"""
response = requests.get(
f"{DOLPHIN_API}/browser_profiles/{profile_id}/start",
headers={"Authorization": f"Bearer {API_TOKEN}"}
)
if response.status_code == 200:
data = response.json()
print(f"프로필 시작됨, WebDriver 포트: {data['automation']['port']}")
return data['automation']['port']
else:
print(f"시작 오류: {response.text}")
# 프로필 시작 및 Selenium을 통한 제어
port = start_profile("profile_id_here")
from selenium import webdriver
driver = webdriver.Remote(
command_executor=f'http://127.0.0.1:{port}',
options=webdriver.ChromeOptions()
)
driver.get("https://facebook.com")
AdsPower 자동화
AdsPower도 로컬 API를 제공합니다. 로직은 Dolphin과 유사하지만 다른 엔드포인트를 사용합니다:
import requests
ADSPOWER_API = "http://local.adspower.net:50325/api/v1"
def create_adspower_profile(name, proxy):
payload = {
"name": name,
"group_id": "0", # 프로필 그룹 ID
"domain_name": "facebook.com",
"open_urls": ["https://facebook.com"],
"repeat_config": ["0"],
"username": proxy["login"],
"password": proxy["password"],
"proxy_type": "http",
"proxy_host": proxy["host"],
"proxy_port": proxy["port"],
"proxy_user": proxy["login"],
"proxy_password": proxy["password"]
}
response = requests.post(
f"{ADSPOWER_API}/user/create",
json=payload
)
if response.json()["code"] == 0:
user_id = response.json()["data"]["id"]
print(f"✓ AdsPower 프로필 생성: {name}, ID: {user_id}")
return user_id
else:
print(f"✗ 오류: {response.json()['msg']}")
# 프로필 생성
for i, proxy in enumerate(proxies):
create_adspower_profile(f"TikTok_Account_{i+1}", proxy)
이러한 자동화는 수십 개의 계정으로 작업할 때 매우 중요합니다. 각 프로필에 프록시 데이터를 수동으로 복사하는 대신 스크립트를 실행하고 몇 분 안에 준비된 인프라를 얻습니다.
오류 처리 및 자동 폴백
프록시로 작업할 때 불가피한 상황이 있습니다: IP가 대상 사이트에 의해 차단됨, 프록시 서버가 응답하지 않음, 트래픽이 소진됨. 적절한 오류 처리는 안정적인 자동화의 핵심입니다.
오류 유형 및 처리 전략
| 오류 | 원인 | 해결책 |
|---|---|---|
| HTTP 403 Forbidden | 사이트 차단 목록의 IP | 프록시 변경, 지연 추가 |
| HTTP 429 Too Many Requests | 속도 제한 초과 | IP 변경, 간격 증가 |
| ProxyError / Timeout | 프록시 서버가 응답하지 않음 | 풀에서 제거, 다음 것 가져오기 |
| 407 Proxy Authentication Required | 잘못된 로그인/비밀번호 | 자격 증명 확인, 업데이트 |
| 페이지의 캡차 | 사이트가 봇을 감지함 | IP 변경, 모바일 프록시 사용 |
스마트 재시도 시스템 구현
단순한 요청 반복 대신 지수 지연과 작동하지 않는 프록시의 블랙리스트가 있는 시스템을 만들어 보겠습니다:
import requests
import time
from collections import defaultdict
class SmartProxyRotator:
def __init__(self, proxy_list):
self.proxy_list = proxy_list
self.blacklist = set() # 작동하지 않는 IP
self.error_count = defaultdict(int) # IP별 오류 카운터
self.max_errors = 3 # 3번 오류 후 — 블랙리스트에
def get_working_proxy(self):
"""블랙리스트에 없는 프록시 가져오기"""
available = [p for p in self.proxy_list if p not in self.blacklist]
if not available:
# 모든 프록시가 차단됨 — 블랙리스트 지우기
print("⚠ 모든 프록시가 차단됨, 블랙리스트 재설정")
self.blacklist.clear()
self.error_count.clear()
available = self.proxy_list
return available[0]
def mark_error(self, proxy):
"""프록시 오류 표시"""
self.error_count[proxy] += 1
if self.error_count[proxy] >= self.max_errors:
self.blacklist.add(proxy)
print(f"✗ 프록시 {proxy}가 블랙리스트에 추가됨")
def request_with_retry(self, url, max_retries=5):
"""스마트 재시도가 있는 요청"""
for attempt in range(max_retries):
proxy = self.get_working_proxy()
try:
# 지수 지연: 1초, 2초, 4초, 8초...
if attempt > 0:
delay = 2 ** attempt
print(f"시도 {attempt+1} 전 {delay}초 대기")
time.sleep(delay)
response = requests.get(
url,
proxies={"http": proxy, "https": proxy},
timeout=15
)
# 성공 — 오류 카운터 재설정
if response.status_code == 200:
self.error_count[proxy] = 0
return response
# 차단 — 프록시 변경
elif response.status_code in [403, 429]:
print(f"상태 {response.status_code}, 프록시 변경 중")
self.mark_error(proxy)
continue
except requests.exceptions.ProxyError:
print(f"{proxy}에서 ProxyError")
self.mark_error(proxy)
except requests.exceptions.Timeout:
print(f"{proxy}에서 Timeout")
self.mark_error(proxy)
raise Exception(f"{max_retries}번 시도 후 요청 실패")
# 사용법:
proxies = [
"http://user:pass@gate1.com:8000",
"http://user:pass@gate2.com:8000",
"http://user:pass@gate3.com:8000",
]
rotator = SmartProxyRotator(proxies)
for i in range(100):
try:
response = rotator.request_with_retry(f"https://api.example.com/data?page={i}")
print(f"✓ 페이지 {i}: {len(response.text)} 바이트")
except Exception as e:
print(f"✗ 페이지 {i}에서 치명적 오류: {e}")
모니터링 및 알림
프로덕션 시스템의 경우 실시간으로 프록시 풀의 상태를 추적하는 것이 중요합니다. 메트릭 로깅을 추가하세요:
import logging
from datetime import datetime
class ProxyMonitor:
def __init__(self):
self.stats = {
"total_requests": 0,
"successful": 0,
"failed": 0,
"proxy_errors": defaultdict(int),
"start_time": datetime.now()
}
# 로깅 설정
logging.basicConfig(
filename='proxy_rotation.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def log_request(self, proxy, success, error=None):
self.stats["total_requests"] += 1
if success:
self.stats["successful"] += 1
logging.info(f"✓ {proxy}에서 성공")
else:
self.stats["failed"] += 1
self.stats["proxy_errors"][proxy] += 1
logging.error(f"✗ {proxy}에서 오류: {error}")
def get_report(self):
uptime = datetime.now() - self.stats["start_time"]
success_rate = (self.stats["successful"] / self.stats["total_requests"] * 100) if self.stats["total_requests"] > 0 else 0
return f"""
=== 프록시 로테이션 보고서 ===
가동 시간: {uptime}
총 요청: {self.stats["total_requests"]}
성공: {self.stats["successful"]} ({success_rate:.1f}%)
오류: {self.stats["failed"]}
문제가 있는 프록시:
{self._format_errors()}
"""
def _format_errors(self):
sorted_errors = sorted(
self.stats["proxy_errors"].items(),
key=lambda x: x[1],
reverse=True
)
return "\n".join([f" {proxy}: {count}개 오류" for proxy, count in sorted_errors[:5]])
# rotator와 통합
monitor = ProxyMonitor()
# 요청 루프에서:
try:
response = rotator.request_with_retry(url)
monitor.log_request(current_proxy, success=True)
except Exception as e:
monitor.log_request(current_proxy, success=False, error=str(e))
모범 사례 및 트래픽 사용 최적화
프록시 로테이션 자동화를 최대한 활용하려면 다음 권장 사항을 따르세요:
1. 작업에 맞는 로테이션 전략 선택
- 소셜 네트워크 계정: 고정 세션 10-30분, 하루에 1-2번 IP 변경
- 마켓플레이스 파싱: 50-100개 요청마다 자동 로테이션
- API 스크래핑: 각 요청마다 새 IP(속도 제한이 엄격한 경우)
- SEO 모니터링: 지역별 고정 세션, 하루 1회 업데이트
2. 요청 간 지연 추가
IP를 변경하더라도 초당 100개의 요청은 의심스럽습니다. 인간의 행동을 모방하세요:
import random
import time
def human_delay():
"""1-5초의 무작위 지연"""
delay = random.uniform(1, 5)
time.sleep(delay)
# 파싱 루프에서
for page in pages:
data = scrape_page(page)
human_delay() # 각 요청 후
3. 프록시 풀 세분화
다양한 작업에 다양한 프록시 그룹을 사용하세요:
proxy_pools = {
"facebook_ads": [/* 미국 주거용 프록시 */],
"instagram": [/* 모바일 프록시 */],
"parsing_wb": [/* 러시아 데이터센터 프록시 */],
"seo_check": [/* 다양한 국가의 프록시 */]
}
# 작업에 따라 풀 선택
if task == "facebook":
rotator = SmartProxyRotator(proxy_pools["facebook_ads"])
4. 트래픽 소비 모니터링
주거용 프록시는 GB당 비용이 청구됩니다. 불필요한 데이터 다운로드를 피하세요:
- 헤드리스 브라우저에서 이미지 비활성화
- 필요한 데이터만 다운로드(전체 HTML 대신 API)
- 응답 압축 사용(gzip)
- 중복 요청 캐싱
# Puppeteer에서 이미지 비활성화
await page.setRequestInterception(true);
page.on('request', (req) => {
if (req.resourceType() === 'image') {
req.abort();
} else {
req.continue();
}
});
5. User-Agent 및 헤더 로테이션
IP 변경만으로는 충분하지 않습니다. 브라우저 지문도 변경하세요:
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36...',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36...'
]
headers = {
'User-Agent': random.choice(user_agents),
'Accept-Language': 'ko-KR,ko;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
6. 프록시 품질 테스트
작업을 시작하기 전에 프록시가 작동하는지 확인하세요:
def test_proxy(proxy):
"""프록시 작동 확인"""
try:
response = requests.get(
'https://api.ipify.org?format=json',
proxies={'http': proxy, 'https': proxy},
timeout=10
)
if response.status_code == 200:
ip = response.json()['ip']
print(f"✓ 프록시 작동: {proxy} → IP: {ip}")
return True
except:
print(f"✗ 프록시 실패: {proxy}")
return False
# 작업 프록시만 필터링
working_proxies = [p for p in all_proxies if test_proxy(p)]
결론
API를 통한 프록시 자동 교체는 현대 파싱, 중재 및 멀티 어카운팅의 기초입니다. 적절한 구현을 통해 다음을 얻을 수 있습니다:
- 생산성 향상: 차단 없이 시간당 수천 개의 요청
- 비용 절감: 트래픽 및 시간의 최적 사용
- 확장성: 수동 개입 없이 수백 개의 계정 관리
- 안정성: 자동 오류 처리 및 폴백
주요 권장 사항:
- 작업에 맞는 프록시 유형 선택: 계정의 경우 주거용, 파싱의 경우 데이터센터
- 스마트 로테이션 구현: 필요할 때만 IP 변경
- 오류 처리 및 재시도 추가
- 메트릭 모니터링 및 로깅
- 인간의 행동 모방: 지연, User-Agent, 헤더
이 가이드의 예제는 Python 및 Node.js에서 프록시 로테이션을 구현하는 기초를 제공합니다. 특정 작업에 맞게 조정하고 프로덕션 환경에서 테스트하세요.
프록시가 필요하신가요? ProxyCove는 API 로테이션, 고정 세션 및 150개 이상 국가의 지리적 타겟팅을 지원하는 주거용 및 모바일 프록시를 제공합니다. 파싱, 중재 및 멀티 어카운팅을 위한 이상적인 솔루션입니다.