Python'da Proxy Kullanımı (Requests + ProxyHat SDK)

Python'da İstekler kütüphanesi ve ProxyHat SDK ile nasıl kullanılacağını öğrenin. Kapaklar kimlik doğrulama, rotasyon, geo-targeting, hata işleme ve async scraping.

Python'da Proxy Kullanımı (Requests + ProxyHat SDK)

Neden Python'da Proxies kullanın?

Python veri çekilmesi manzarasını hakim eder. Kütüphaneler gibi kütüphaneler İstekler, httpxVe Yararlı HTTP önemsiz diyor, ancak proxy olmadan, senaryolarınız birkaç dakika içinde IP yasaklarını vurdu. Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Using Python'da Kaynaklar IP adreslerini döndürün, geo-restrictions'ı atlayın ve kazı operasyonlarınızı güvenilir bir şekilde ölçeklendirmenize izin verin.

Bu kılavuzda, temsilcileri Python'a nasıl entegre edeceğinizi öğreneceksiniz ProxyHat Python SDK Ve standart requests Kütüphane. Her bölüm hemen çalıştırabileceğiniz kopya-paste-ready kodunu içermektedir.

İsterseniz Web scraping pipeline, izleme SERP sonuçları, veya fiyatlandırma verilerini toplamak, bu kılavuz kimlik doğrulamayı, proxy rotasyonunu, geo-targeting, hata işlemeyi ve üretim ölçeklendirmesini kapsar.

Kurulum ve Kurulum

ProxyHat SDK'sını yükleyin ve İstekler

ProxyHat Python SDK ve the requests Boru kullanarak kütüphane:

pip install proxyhat requests

Async iş akışları için, aynı zamanda yükleme httpx ve aiohttp:

pip install httpx aiohttp

API Credentials

kaydolun ProxyHat API anahtarını panodan alın. Size ihtiyacınız olacak Kullanıcı adı ve şifre şifre şifre (veya API anahtarı) proxy doğrulama için. Tam kimlik doğrulama detayları mevcuttur ProxyHat API belgeleri.

Doğrulama ve Temel Yapılama

ProxyHat SDK'sını kullanarak

SDK sizin için kimlik doğrulama, rotasyon ve bağlantı yönetimi yönetiyor:

from proxyhat import ProxyHat
client = ProxyHat(
    api_key="your_api_key_here"
)
# Test the connection
info = client.get_account_info()
print(f"Traffic remaining: {info['traffic_remaining']} GB")

Raw Proxy Credentials with Requests

Eğer kullanmayı tercih ederseniz requests Doğrudan, proxy URL'sini yapılandırın:

import requests
proxy_url = "http://username:password@gate.proxyhat.com:8080"
proxies = {
    "http": proxy_url,
    "https": proxy_url,
}
response = requests.get(
    "https://httpbin.org/ip",
    proxies=proxies,
    timeout=30
)
print(response.json())
# {"origin": "185.xxx.xxx.xxx"}

Basit GET Proxy with a Proxy

İşte bir ProxyHat konutu aracılığıyla bir GET isteği gönderen tam bir örnek:

from proxyhat import ProxyHat
client = ProxyHat(api_key="your_api_key_here")
# Make a proxied GET request
response = client.get("https://httpbin.org/ip")
print(f"Status: {response.status_code}")
print(f"IP: {response.json()['origin']}")
print(f"Headers: {response.headers}")

Veya standart ile requests Kütüphane:

import requests
proxies = {
    "http": "http://user:pass@gate.proxyhat.com:8080",
    "https": "http://user:pass@gate.proxyhat.com:8080",
}
response = requests.get(
    "https://example.com/api/data",
    proxies=proxies,
    timeout=30,
    headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
)
print(response.status_code)
print(response.text[:500])

Doğru Proxy Type seçmek

ProxyHat üç proxy türü sunuyor. Kullanım durumunuza dayanarak seçin. Daha derin bir karşılaştırma için rehberimizi okuyun Konut vs datacenter vs mobil proxy.

Doğru Proxy Type seçmek
Tipi Tipi Tipi TipiEn iyisi içinHız Hız Hız HızTespit RiskiMaliyet Maliyet Maliyet Maliyet Maliyet
Konut Konut Konut KonutWeb scraping, SERP takipMedium Medium Medium Medium MediumÇok düşükPer GB
DatacenterYüksek hacimli, hız kritik görevlerHızlı Hızlı Hızlı HızlıDaha yüksekIP / ay
Mobile Mobile MobileSosyal medya, uygulama testleriMedium Medium Medium Medium MediumEn düşükPer GB

Proxy Tiplerini Kodlama

from proxyhat import ProxyHat
client = ProxyHat(api_key="your_api_key_here")
# Residential proxy (default)
response = client.get(
    "https://example.com",
    proxy_type="residential"
)
# Datacenter proxy
response = client.get(
    "https://example.com",
    proxy_type="datacenter"
)
# Mobile proxy
response = client.get(
    "https://example.com",
    proxy_type="mobile"
)

Bloking vs Sticky Sessions

Rotating proxy Her istek için yeni bir IP atamak, maksimum anonimliğe ihtiyacınız olan büyük ölçekli kazı için ideal. Sticky seansları Aynı IP'yi belirli bir süre için, giriş dizileri veya paginated navigasyon gibi çoklu adım akışları için tut.

Rotating Proxies (Yeni IP Her İstek)

from proxyhat import ProxyHat
client = ProxyHat(api_key="your_api_key_here")
urls = [
    "https://httpbin.org/ip",
    "https://httpbin.org/ip",
    "https://httpbin.org/ip",
]
for url in urls:
    response = client.get(url, session_type="rotating")
    print(f"IP: {response.json()['origin']}")
# Each request uses a different IP:
# IP: 185.xxx.xxx.1
# IP: 92.xxx.xxx.47
# IP: 78.xxx.xxx.203

Sticky Sessions (Same IP for Duration)

from proxyhat import ProxyHat
client = ProxyHat(api_key="your_api_key_here")
# Create a sticky session (maintains IP for up to 30 minutes)
session = client.create_session(duration_minutes=30)
# All requests in this session use the same IP
for page in range(1, 6):
    response = session.get(f"https://example.com/products?page={page}")
    print(f"Page {page}: IP {response.headers.get('X-Proxy-IP')}")
# Same IP across all pages:
# Page 1: IP 185.xxx.xxx.42
# Page 2: IP 185.xxx.xxx.42
# Page 3: IP 185.xxx.xxx.42

Geo-Targeted Requests

Belirli bir ülkeden veriye mi ihtiyacınız var? ProxyHat destek 195+ lokasyonda geo-targeting. Bu, yerelleştirilmiş SERP hurdalama, fiyat izleme ve içerik doğrulama için kritik.

from proxyhat import ProxyHat
client = ProxyHat(api_key="your_api_key_here")
# Target a specific country
response = client.get(
    "https://www.google.com/search?q=best+restaurants",
    country="US"
)
# Target a specific city
response = client.get(
    "https://www.google.com/search?q=best+restaurants",
    country="US",
    city="New York"
)
# Using raw proxy URL with geo-targeting
# Format: username-country-US:password@gate.proxyhat.com:8080
import requests
proxies = {
    "http": "http://user-country-DE:pass@gate.proxyhat.com:8080",
    "https": "http://user-country-DE:pass@gate.proxyhat.com:8080",
}
response = requests.get("https://www.google.de", proxies=proxies, timeout=30)
print(f"Accessed from Germany: {response.status_code}")

Hata işleme ve Retries

Ağ talepleri başarısız olur. Proxies zamanout. Hedefler sizi bloke eder. Robust hatası, toy scripts'tan ayrı üretim hurdalarını işletir.

Temel Retry Mantık

import time
import requests
from requests.exceptions import ProxyError, Timeout, ConnectionError
def fetch_with_retry(url, proxies, max_retries=3, timeout=30):
    """Fetch a URL with automatic retry on failure."""
    for attempt in range(max_retries):
        try:
            response = requests.get(
                url,
                proxies=proxies,
                timeout=timeout,
                headers={"User-Agent": "Mozilla/5.0"}
            )
            response.raise_for_status()
            return response
        except (ProxyError, Timeout, ConnectionError) as e:
            wait = 2 ** attempt  # Exponential backoff
            print(f"Attempt {attempt + 1} failed: {e}. Retrying in {wait}s...")
            time.sleep(wait)
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 429:
                wait = 10 * (attempt + 1)
                print(f"Rate limited. Waiting {wait}s...")
                time.sleep(wait)
            elif e.response.status_code >= 500:
                time.sleep(2 ** attempt)
            else:
                raise
    raise Exception(f"Failed to fetch {url} after {max_retries} attempts")
# Usage
proxies = {
    "http": "http://user:pass@gate.proxyhat.com:8080",
    "https": "http://user:pass@gate.proxyhat.com:8080",
}
response = fetch_with_retry("https://example.com/data", proxies)

SDK'nın İnşa Edilmesini Kullanın

from proxyhat import ProxyHat
client = ProxyHat(
    api_key="your_api_key_here",
    max_retries=3,
    timeout=30,
    retry_on_status=[429, 500, 502, 503]
)
# The SDK handles retries automatically
response = client.get("https://example.com/data")
print(response.status_code)

Concurrent Hearing with Threading

Eşit istekler yavaştır. Üretim iş yükleri için Python'un kullanımını kullanın concurrent.futures İstekleri temsilciler aracılığıyla paralelleştirmek.

from concurrent.futures import ThreadPoolExecutor, as_completed
from proxyhat import ProxyHat
client = ProxyHat(api_key="your_api_key_here")
urls = [
    "https://example.com/product/1",
    "https://example.com/product/2",
    "https://example.com/product/3",
    "https://example.com/product/4",
    "https://example.com/product/5",
]
def scrape(url):
    """Scrape a single URL through the proxy."""
    response = client.get(url, proxy_type="residential")
    return {"url": url, "status": response.status_code, "length": len(response.text)}
# Run 5 concurrent requests
results = []
with ThreadPoolExecutor(max_workers=5) as executor:
    futures = {executor.submit(scrape, url): url for url in urls}
    for future in as_completed(futures):
        try:
            result = future.result()
            results.append(result)
            print(f"OK: {result['url']} ({result['length']} bytes)")
        except Exception as e:
            print(f"Error: {futures[future]} - {e}")
print(f"\nCompleted: {len(results)}/{len(urls)}")

asyncio ve httpx

import asyncio
import httpx
async def scrape_urls(urls, proxy_url, max_concurrent=10):
    """Scrape multiple URLs concurrently using async proxies."""
    semaphore = asyncio.Semaphore(max_concurrent)
    async def fetch(client, url):
        async with semaphore:
            response = await client.get(url, timeout=30)
            return {"url": url, "status": response.status_code}
    async with httpx.AsyncClient(proxy=proxy_url) as client:
        tasks = [fetch(client, url) for url in urls]
        return await asyncio.gather(*tasks, return_exceptions=True)
# Usage
proxy_url = "http://user:pass@gate.proxyhat.com:8080"
urls = [f"https://example.com/page/{i}" for i in range(1, 51)]
results = asyncio.run(scrape_urls(urls, proxy_url))
successful = [r for r in results if not isinstance(r, Exception)]
print(f"Scraped {len(successful)}/{len(urls)} pages")

Popüler Python Kütüphaneleri ile entegrasyon

İsteklerle Kullanımı (Session)

import requests
session = requests.Session()
session.proxies = {
    "http": "http://user:pass@gate.proxyhat.com:8080",
    "https": "http://user:pass@gate.proxyhat.com:8080",
}
session.headers.update({
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
})
# All requests in this session use the proxy
response = session.get("https://example.com/api/products")
print(response.json())

httpx ile kullanım

import httpx
proxy_url = "http://user:pass@gate.proxyhat.com:8080"
# Synchronous
with httpx.Client(proxy=proxy_url) as client:
    response = client.get("https://httpbin.org/ip")
    print(response.json())
# Asynchronous
async with httpx.AsyncClient(proxy=proxy_url) as client:
    response = await client.get("https://httpbin.org/ip")
    print(response.json())

Aiohttp ile kullanım

import aiohttp
import asyncio
async def fetch_with_aiohttp():
    proxy_url = "http://user:pass@gate.proxyhat.com:8080"
    async with aiohttp.ClientSession() as session:
        async with session.get(
            "https://httpbin.org/ip",
            proxy=proxy_url,
            timeout=aiohttp.ClientTimeout(total=30)
        ) as response:
            data = await response.json()
            print(f"IP: {data['origin']}")
asyncio.run(fetch_with_aiohttp())

Yararlı ile kullanımı

Yararlı örümcekinize ProxyHat ekleyiniz settings.py:

# settings.py
DOWNLOADER_MIDDLEWARES = {
    "scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware": 110,
}
HTTP_PROXY = "http://user:pass@gate.proxyhat.com:8080"
# Or set per-request in your spider:
import scrapy
class ProductSpider(scrapy.Spider):
    name = "products"
    start_urls = ["https://example.com/products"]
    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(
                url,
                meta={"proxy": "http://user:pass@gate.proxyhat.com:8080"},
                callback=self.parse
            )
    def parse(self, response):
        for product in response.css(".product-card"):
            yield {
                "name": product.css("h2::text").get(),
                "price": product.css(".price::text").get(),
            }

Üretim İpuçları

Bağlantı Havuz ve Zamanlar

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
# Configure retry strategy
retry_strategy = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(
    max_retries=retry_strategy,
    pool_connections=10,
    pool_maxsize=20
)
session.mount("http://", adapter)
session.mount("https://", adapter)
session.proxies = {
    "http": "http://user:pass@gate.proxyhat.com:8080",
    "https": "http://user:pass@gate.proxyhat.com:8080",
}
# Robust, production-ready request
response = session.get("https://example.com/data", timeout=(5, 30))
print(response.status_code)

Logging ve İzleme

import logging
import time
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
logger = logging.getLogger("scraper")
def monitored_request(session, url):
    """Log request timing and status for monitoring."""
    start = time.time()
    try:
        response = session.get(url, timeout=30)
        elapsed = time.time() - start
        logger.info(f"OK {response.status_code} {url} ({elapsed:.2f}s)")
        return response
    except Exception as e:
        elapsed = time.time() - start
        logger.error(f"FAIL {url} ({elapsed:.2f}s): {e}")
        raise

Çevre Credentials için Değişkenler

Hiçbir zaman zor kod kimlikleri. Çevre değişkenlerini kullanın:

import os
from proxyhat import ProxyHat
client = ProxyHat(
    api_key=os.environ["PROXYHAT_API_KEY"]
)
# Or with raw proxy URL
proxy_url = os.environ.get(
    "PROXY_URL",
    "http://user:pass@gate.proxyhat.com:8080"
)

Mevcut proxy planlarının ve trafik seçeneklerinin tam bir listesi için, ziyaret edin Fiyat sayfasıGelişmiş kullanım koşulları ve uç nokta referansı için, bakınız API belgeleriAyrıca rehberimizi inceleyebilirsiniz Web için en iyi proxy 2026 Sağlayıcı karşılaştırmalar için.

Key Takeaways

  • Bir komutta yükleme: pip install proxyhat requests Hemen başladın.
  • SDK'yı basitleştirmek için kullanın: ProxyHat Python SDK doğrulamayı, tekrarlamaları ve rotasyonu otomatik olarak ele alır.
  • Doğru tip proxy seçin: Çekilme, hız için merkezi veriler, sosyal platformlar için mobil.
  • Rotate vs çubuğu: Çok adımlı iş akışları için geri dönüşümlü proxy kullanın.
  • İhtiyacınız olduğunda Geo-target: Yerelleştirilmiş veri toplama için ülke ve şehir.
  • Hataları düzgün bir şekilde şarj edin: Üretim güvenilirliği için üst üste ve yeniden deneme mantığı uygulayın.
  • Koncurrency ile Ölçek: Use Use Use Use Use Use ThreadPoolExecutor veya asyncio İstekleri paralelleştirmek için.
  • Hiçbir zaman zor kod referansları: Mağaza API anahtarları çevre değişkenleri.

Sık Sorulan Sorular

Python İsteklerinde bir proxy nasıl kurdum?

Geçin proxies Herhangi bir sözlüğe requests Yöntem: requests.get(url, proxies={"http": "http://user:pass@host:port", "https": "http://user:pass@host:port"}). ProxyHat SDK bunu, proxy yapılandırmasını içsel olarak kullanarak daha da basitleştirir.

Python'daki dönen ve yapışkanlar arasındaki fark nedir?

Rotating agents, büyük ölçekli kazı için ideal olan her istek için yeni bir IP adresi tayin eder. Stickyants aynı IP'yi belirli bir süre için koruyor (örneğin, 10-30 dakika), giriş seansları, alışveriş arabaları veya IP tutarlılık önemli olan paginated tarama için gereklidir.

ProxyHat proxylerini asyncio ve aiohttp ile kullanabilir miyim?

Evet. ProxyHat proxy, proxy yapılandırmasını destekleyen herhangi bir HTTP müşteri ile çalışır, dahil aiohttp, httpx (async modu) ve asyncio- temelli çerçeveler. URL proxy'yi as the proxy Async müşterinizde parametre.

Python'da proxy hatalarını ve zamanlarını nasıl idare ediyorum?

İsteklerinizi deneyin / bloklar yakalama dışında ProxyError, TimeoutVe ConnectionError. Implement üstel backoff (öğrenmeler arasında zaman beklemek) ve maksimum bir retry sayımı belirledi. ProxyHat SDK, yapılandırılabilir parametrelerle yeniden deneme mantığını içerir.

Hangi Python kütüphanesi, referanslarla dolu web için en iyisidir?

Basit görevler için, requests ProxyHat SDK ile en kolay seçenektir. Yüksek hacimli için, kullanımı kullanın httpx veya aiohttp. Karmaşık tarama için aşağıdaki ve veri ekstraksiyonu ile, Scrapy Orta proxy ile en güçlü seçimdir. Tüm çalışmalar ProxyHat proxy ile sorunsuz bir şekilde çalışır.

Başlamaya hazır mısınız?

148+ ülkede 50M+ konut IP'sine AI destekli filtreleme ile erişin.

Fiyatlandırmayı GörüntüleKonut Proxy'leri
← Bloga Dön