Integration

Shifter verwenden mit Python

Integrieren Sie Shifters Residential- und ISP-Proxys in wenigen Minuten in Ihre Python-Skripte. Funktioniert nahtlos mit requests, aiohttp, Scrapy, Selenium und allen wichtigen Python-HTTP-Bibliotheken.

Schnellstart

Installieren

pip install requests

Grundlegende Nutzung

import requests

proxy_url = "customer-USERNAME-country-us-sid-123ABC:PASSWORD@p.shifter.io:443"

proxies = {
    "http": proxy_url,
    "https": proxy_url,
}

response = requests.get("https://ipinfo.io/json", proxies=proxies)
print(response.json())
# {"ip": "154.16.xxx.xxx", "city": "New York", "country": "US", ...}

Funktionen

Kompatibel mit allen Python-HTTP-Bibliotheken, einschließlich requests, aiohttp, httpx und urllib3
Automatische IP-Rotation pro Anfrage, pro Session (sid) oder über konfigurierbare Sticky Sessions (ttl)
Vollständige Unterstützung für HTTP- und SOCKS5-Proxy-Protokolle
Kompatibel mit Python 3.7+ und allen wichtigen Scraping-Frameworks wie Scrapy und BeautifulSoup
Geo-Targeting-Unterstützung, Proxys aus 195+ Ländern über einfache Benutzernamen-Parameter auswählen
Kein zusätzliches SDK erforderlich, Shifter über Standard-Proxy-Umgebungsvariablen oder Inline-Einstellungen konfigurieren

Beispiele

Grundlegende Requests

Die einfachste Möglichkeit, Shifter-Proxys mit Pythons beliebtester HTTP-Bibliothek zu verwenden. Legen Sie Land, Region, Stadt oder ASN direkt im Benutzernamen fest und übergeben Sie eine `sid`, um dieselbe IP über mehrere Anfragen hinweg beizubehalten.

import requests

PROXY_USER = "customer-USERNAME-country-us-sid-123ABC"
PROXY_PASS = "PASSWORD"
PROXY_HOST = "p.shifter.io"
PROXY_PORT = "443"

proxies = {
    "http": f"http://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}",
    "https": f"http://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}",
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}

response = requests.get(
    "https://example.com",
    proxies=proxies,
    headers=headers,
    timeout=30,
)

print(f"Status: {response.status_code}")
print(f"Content length: {len(response.text)}")

Async mit aiohttp + Sticky Sessions

Verwenden Sie aiohttp für leistungsstarkes asynchrones Scraping. Fügen Sie `sid-XXX` zum Benutzernamen hinzu, um dieselbe IP über mehrere Anfragen hinweg beizubehalten, oder `ttl-N` für eine zeitgesteuerte Sticky Session von N Sekunden.

import aiohttp
import asyncio
import uuid

# sid pins the same IP for every request that shares this session id;
# ttl-300 keeps that IP for up to 300 seconds, then rotates.
session_id = uuid.uuid4().hex[:8]
PROXY_URL = (
    f"customer-USERNAME-country-us-sid-{session_id}-ttl-300:"
    f"PASSWORD@p.shifter.io:443"
)

async def fetch(session, url):
    async with session.get(
        url, proxy=PROXY_URL, timeout=aiohttp.ClientTimeout(total=30)
    ) as response:
        return await response.text()

async def main():
    urls = [
        "https://example.com/login",
        "https://example.com/dashboard",
        "https://example.com/orders",
    ]

    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks, return_exceptions=True)

        for url, result in zip(urls, results):
            if isinstance(result, Exception):
                print(f"Error fetching {url}: {result}")
            else:
                print(f"Fetched {url}: {len(result)} bytes")

asyncio.run(main())

Scrapy Middleware

Integrieren Sie Shifter-Proxys in Ihre Scrapy-Spider mit einer benutzerdefinierten Downloader-Middleware. Geo-Targeting durch Hinzufügen von Selektoren wie `country-uk`, `region-bavaria`, `city-london` oder `asn-7922` zum Benutzernamen, und fixieren Sie die Session mit einer `sid`.

# middlewares.py
class ShifterProxyMiddleware:
    PROXY_USER = "customer-USERNAME-country-uk-sid-456DEF"
    PROXY_PASS = "PASSWORD"
    PROXY_HOST = "p.shifter.io"
    PROXY_PORT = "443"

    def process_request(self, request, spider):
        request.meta["proxy"] = (
            f"http://{self.PROXY_USER}:{self.PROXY_PASS}"
            f"@{self.PROXY_HOST}:{self.PROXY_PORT}"
        )

# settings.py
DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.ShifterProxyMiddleware": 350,
}

# spider.py
import scrapy

class ProductSpider(scrapy.Spider):
    name = "products"
    start_urls = ["https://example.co.uk/products"]

    def parse(self, response):
        for product in response.css(".product-card"):
            yield {
                "title": product.css("h2::text").get(),
                "price": product.css(".price::text").get(),
                "url": product.css("a::attr(href)").get(),
            }

        next_page = response.css("a.next-page::attr(href)").get()
        if next_page:
            yield response.follow(next_page, self.parse)

Selenium WebDriver

Leiten Sie die Selenium-Browserautomatisierung über Shifter-Proxys. Ideal für das Scraping von JavaScript-gerenderten Seiten. Kombinieren Sie stadtgenaues Targeting mit einer `sid`, um dieselbe IP für die gesamte Browser-Session beizubehalten.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PROXY_HOST = "p.shifter.io"
PROXY_PORT = "443"
PROXY_USER = "customer-USERNAME-country-us-city-newyork-sid-789GHI"
PROXY_PASS = "PASSWORD"

chrome_options = Options()
chrome_options.add_argument(
    f"--proxy-server=http://{PROXY_HOST}:{PROXY_PORT}"
)

driver = webdriver.Chrome(options=chrome_options)

# Handle proxy authentication via browser extension or seleniumwire if needed
driver.get("https://example.com")

# Wait for dynamic content to load
wait = WebDriverWait(driver, 10)
element = wait.until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".content"))
)

print(f"Page title: {driver.title}")
print(f"Content: {element.text[:200]}")

driver.quit()
FAQ

Häufig gefragt FAQ-Fragen

Häufige Fragen zur Verwendung von Shifter mit Python.

Übergeben Sie ein proxies-Dictionary an jede requests-Methode mit Ihrer Shifter-Proxy-URL. Das Format lautet: proxies = {"http": "customer-USERNAME-country-us-sid-123ABC:PASSWORD@p.shifter.io:443", "https": "customer-USERNAME-country-us-sid-123ABC:PASSWORD@p.shifter.io:443"}. Rufen Sie dann requests.get(url, proxies=proxies) auf.

Jetzt starten

Shifter verwenden mit Python

Integrieren Sie Shifters 205M+ Residential-Proxys in unter 5 Minuten in Ihre Python-Skripte. Flexible IP-Rotation, Geo-Targeting und vollständige Kompatibilität mit allen wichtigen Python-Bibliotheken.

Shifter kostenlos testenIn Minuten eingerichtet. Jederzeit kuendbar.