Proxies in Python verwenden (Requests + ProxyHat SDK)

Erfahren Sie, wie man Proxies in Python mit der Request-Bibliothek und ProxyHat SDK verwendet. Abdeckungen Authentifizierung, Rotation, Geotargeting, Fehlerbehandlung und Async-Schrott.

Proxies in Python verwenden (Requests + ProxyHat SDK)

Warum Proxies in Python verwenden?

Python dominiert die Datenextraktionslandschaft. Bibliotheken wie Anträge, httpx, und Schrott Machen Sie HTTP-Anrufe trivial, aber ohne Proxies, Ihre Skripte treffen IP-Banns innerhalb von Minuten. Verwendung Proxies in Python Sie können IP-Adressen drehen, Geobeschränkungen umgehen und Ihre Abstreifvorgänge zuverlässig skalieren.

In diesem Leitfaden lernen Sie, wie man Proxies in Python integriert ProxyHat Python SDK und der Standard requests Bibliothek. Jeder Abschnitt enthält den Kopier-Pasta-ready-Code, den Sie sofort ausführen können.

Ob Sie ein Web-Schrott Rohrleitung, Überwachung SERP Ergebnisse, oder das Sammeln von Preisdaten, dieser Leitfaden umfasst Authentifizierung, Proxy-Rotation, Geo-Targeting, Fehlerbehandlung und Produktionsskalierung.

Installation und Inbetriebnahme

Installieren der ProxyHat SDK und Anfragen

Installieren Sie das ProxyHat Python SDK und das requests Bibliothek mit pip:

pip install proxyhat requests

Für async Workflows, auch installieren httpx und aiohttp:

pip install httpx aiohttp

Erhalten Sie Ihre API-Ergebnisse

Anmeldung bei ProxyHat und Ihre API-Taste aus dem Dashboard abrufen. Sie benötigen Ihre Benutzername und Passwort vergessen? (oder API-Schlüssel) für die Proxy-Authentifizierung. Volle Authentifizierungsdetails sind in der ProxyHat API Dokumentation.

Authentifizierung und Grundkonfiguration

Verwendung des ProxyHat SDK

Das SDK behandelt Authentifizierung, Rotation und Verbindungsmanagement für Sie:

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

Verwenden von Raw Proxy-Ergebnisse mit Anfragen

Wenn Sie es bevorzugen requests direkt die Proxy-URL konfigurieren:

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

Einfaches GET Anfrage mit einem Proxy

Hier ist ein komplettes Beispiel, das eine GET-Anfrage durch eine ProxyHat-Bewohnungs-Proxy sendet:

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

Oder mit dem Standard requests Bibliothek:

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])

Wahl des richtigen Proxy-Typs

ProxyHat bietet drei Proxytypen. Wählen Sie basierend auf Ihrem Anwendungsfall. Für einen tieferen Vergleich, lesen Sie unsere Anleitung auf Wohnen vs datacenter vs mobile proxies.

Wahl des richtigen Proxy-Typs
TypDas Beste fürGeschwindigkeitNachweisrisikoKosten
WohngebietWeb-Schrott, SERP-TrackingMittelSehr niedrigPro GB
DatencenterHochvolumige, geschwindigkeitskritische AufgabenSchnellHöherPro IP/Monat
MobilSocial Media, App-TestsMittelNiedrigstenPro GB

Schalten von Proxy-Typen in Code

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

Rotating vs Sticky Sessions

Rotierende Proxis Senden Sie eine neue IP für jede Anfrage, ideal für großformatige Abstreifung, wo Sie maximale Anonymität benötigen. Sticky Sessions Halten Sie die gleiche IP für eine bestimmte Dauer, die für mehrstufige Workflows wie Login-Sequenzen oder paginierte Navigation unerlässlich ist.

Rotating Proxies (Neue IP Jede Anfrage)

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 für Dauer)

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 Anfragen

Brauchen Sie Daten aus einem bestimmten Land? ProxyHat unterstützt geo-targeting über 195+ Standorte. Dies ist entscheidend für lokalisiertes SERP-Schrotten, Preisüberwachung und Inhaltsprüfung.

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

Fehlerbehandlung und Retries

Netzwerkanfragen scheitern. Proxies Timeout. Ziele blockieren Sie. Robuste Fehlerbehandlung trennt Produktionsabstreifer von Spielzeugskripten.

Basic Retry Logic

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)

Verwendung der integrierten SDK-Retry

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 Scraping mit Gewinde

Folgewünsche sind langsam. Für Produktionsarbeiten verwenden Sie Pythons concurrent.futures Anfragen durch Proxies parallelisieren.

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

Async Scraping mit Asyncio und 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")

Integration mit beliebten Python Libraries

Verwendung mit Anfragen (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())

Verwendung von httpx

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())

Verwendung von aiohttp

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())

Mit Scrapy

Fügen Sie ProxyHat zu Ihrer Scrapy Spinne hinzu, indem Sie die 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(),
            }

Produktionstipps

Anschluss Pooling und Timeouts

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)

Protokollierung und Überwachung

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

Umgebungsvariablen für Anmeldeinformationen

Nie Hardcode Anmeldeinformationen. Verwenden Sie Umgebungsvariablen:

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

Für eine vollständige Liste der verfügbaren Proxypläne und Verkehrsoptionen, besuchen Sie unsere Seite. Für fortgeschrittene Anwendungsfälle und Endpunktreferenz siehe die API-Dokumentation. Sie können auch unsere Anleitung auf der beste Proxies für Web-Schrott in 2026 für Anbietervergleiche.

Schlüsselanhänger

  • Installieren Sie in einem Befehl: pip install proxyhat requests Sie werden sofort gestartet.
  • Verwenden Sie das SDK für Einfachheit: Das ProxyHat Python SDK behandelt automatisch Authentifizierung, Retries und Rotation.
  • Wählen Sie den richtigen Proxytyp: Wohnort für Schrott, Rechenzentrum für Geschwindigkeit, mobil für soziale Plattformen.
  • Rotieren vs Stick: Verwenden Sie rotierende Proxies für Schüttgutschrott, klebrige Sessions für mehrstufige Workflows.
  • Geotarget bei Bedarf: Geben Sie Land und Stadt für die lokale Datenerhebung an.
  • Fehler richtig handhaben: Ergänzen Sie exponentielle Backoff- und Retry-Logik für die Produktionssicherheit.
  • Waage mit Konkurs: Verwendung ThreadPoolExecutor oder asyncio die Anfragen parallelisieren.
  • Nie Hardcode Anmeldeinformationen: Speichern Sie API-Tasten in Umgebungsvariablen.

Häufig gestellte Fragen

Wie erstelle ich einen Proxy in Python Requests?

Passen Sie proxies Wörterbuch für jedes requests Methode: requests.get(url, proxies={"http": "http://user:pass@host:port", "https": "http://user:pass@host:port"})Die ProxyHat SDK vereinfacht dies weiter, indem sie die Proxykonfiguration intern handhabt.

Was ist der Unterschied zwischen rotierenden und klebrigen Proxien in Python?

Rotierende Proxies vergeben eine neue IP-Adresse für jede Anfrage, die ideal für großflächiges Abkratzen ist. Sticky-Proxies halten die gleiche IP für eine bestimmte Dauer (z.B. 10-30 Minuten), die für Login-Sitzungen, Einkaufswagen oder paginierte Browser, wo IP-Konsistenz wichtig ist.

Kann ich ProxyHat-Proxies mit Asyncio und aiohttp verwenden?

Ja. ProxyHat-Proxies arbeiten mit jedem HTTP-Client, der die Proxy-Konfiguration unterstützt, einschließlich aiohttp, httpx (async mode) und asyncio-basierte Rahmenbedingungen. Die Proxy-URL als die proxy Parameter in Ihrem Async Client.

Wie behandle ich Proxy-Fehler und Timeouts in Python?

Wrapieren Sie Ihre Anfragen in versuchen/ausgenommen Blöcke fangen ProxyError, Timeout, und ConnectionError. Ergänzen Sie exponentielle Backoff (doubling wait time between retries) und setzen Sie eine maximale Retry count. Das ProxyHat SDK enthält integrierte Retry-Logik mit konfigurierbaren Parametern.

Welche Python-Bibliothek ist am besten für Web Scraping mit Proxies?

Für einfache Aufgaben, requests mit dem ProxyHat SDK ist die einfachste Option. Für hochkoncurrency Async Scraping, verwenden httpx oder aiohttp. Für komplexes Crawlen mit Linkfolge und Datenextraktion, Scrapy mit Proxy Middleware ist die mächtigste Wahl. Alle arbeiten nahtlos mit ProxyHat-Proxies.

Bereit loszulegen?

Zugang zu über 50 Mio. Residential-IPs in über 148 Ländern mit KI-gesteuerter Filterung.

Preise ansehenResidential Proxies
← Zurück zum Blog