Proxy ile Hata Yönetimi ve Retry Stratejileri
1 viewsProxy ile Hata Yönetimi ve Retry Stratejileri
Web scraping ve otomasyon projelerinde proxy kullanırken en sık karşılaşılan sorun bağlantı hatalarıdır. Proxy sunucuları zaman zaman yavaşlayabilir, kapanabilir veya hedef site tarafından engellenebilir.
Bu makalede proxy hatalarını profesyonel şekilde nasıl yöneteceğinizi anlatacağız.
1. Proxy ile Karşılaşılan Yaygın Hatalar
| Hata Türü | Açıklama | Sıklık |
|---|---|---|
| ProxyError | Proxy sunucusuna bağlanılamıyor | Yüksek |
| ConnectTimeout | Proxy yavaş veya erişilemez | Yüksek |
| SSLError | HTTPS bağlantı sorunu | Orta |
| ConnectionError | Genel bağlantı hatası | Yüksek |
| TooManyRedirects | Proxy yönlendirme sorunu | Orta |
| HTTPError (4xx, 5xx) | Hedef site hatası | Orta |
2. Basit Retry Stratejisi (Manuel)
Python
import requests import time import random def request_with_retry(url, proxies, max_retries=3): for attempt in range(max_retries): try: response = requests.get(url, proxies=proxies, timeout=10) if response.status_code == 200: return response except Exception as e: print(f"Deneme {attempt + 1} başarısız: {e}") time.sleep(random.uniform(1, 3)) # Rastgele bekleme return None
3. Profesyonel Retry: tenacity Kütüphanesi
tenacity, Python’da en popüler retry kütüphanesidir.
Bash
pip install tenacity
Exponential Backoff ile Retry Örneği:
Python
import requests from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type @retry( stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=2, max=10), retry=retry_if_exception_type((requests.exceptions.ProxyError, requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError)) ) def fetch_with_proxy(url, proxies): response = requests.get(url, proxies=proxies, timeout=10) response.raise_for_status() return response # Kullanım proxies = {"http": "http://proxy_ip:8080", "https": "http://proxy_ip:8080"} try: result = fetch_with_proxy("https://example.com", proxies) print(result.text) except Exception as e: print(f"Tüm denemeler başarısız: {e}")
4. Proxy Rotasyonu ile Retry Stratejisi
Hata aldığınızda proxy’yi değiştirerek devam etmek daha akıllıcadır:
Python
import requests import random from tenacity import retry, stop_after_attempt, wait_fixed PROXIES = [ "http://proxy1:8080", "http://proxy2:8080", "http://kullanici:sifre@proxy3:3128" ] @retry(stop=stop_after_attempt(3), wait=wait_fixed(2)) def fetch_with_rotation(url): proxy = random.choice(PROXIES) proxies = {"http": proxy, "https": proxy} try: response = requests.get(url, proxies=proxies, timeout=10) return response except Exception as e: print(f"Proxy {proxy} başarısız, yeni proxy deneniyor...") raise # tenacity'nin tekrar denemesini sağlar
5. Gelişmiş Strateji: Proxy + Retry + Logging
Python
import requests import logging from tenacity import retry, stop_after_attempt, wait_exponential logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @retry( stop=stop_after_attempt(4), wait=wait_exponential(multiplier=1, min=2, max=15), before_sleep=lambda retry_state: logger.warning( f"Retry {retry_state.attempt_number} - Hata: {retry_state.outcome.exception()}" ) ) def robust_request(url, proxies): response = requests.get(url, proxies=proxies, timeout=12) response.raise_for_status() return response
6. En İyi Uygulamalar
| Uygulama | Açıklama |
|---|---|
| Exponential Backoff | Her denemede bekleme süresini artır |
| Proxy Rotasyonu | Hata durumunda proxy değiştir |
| Logging | Hangi proxy’nin ne zaman hata verdiğini kaydet |
| Farklı Hata Türlerine Özel Retry | Sadece bağlantı hatalarında retry yap |
| Circuit Breaker Pattern | Çok fazla hata alınırsa geçici olarak dur |
Sonuç
Proxy ile çalışırken hata yönetimi, projenizin kararlılığını doğrudan etkiler. Basit try-except blokları yerine tenacity gibi kütüphaneler kullanarak profesyonel retry stratejileri uygulayabilirsiniz.
Özellikle proxy rotasyonu ile birleştirildiğinde hem daha dayanıklı hem de daha verimli sistemler kurabilirsiniz.
Bir sonraki makalemizde Playwright ile Proxy Kullanımı konusunu detaylı olarak inceleyeceğiz.