통합

Shifter와 함께 사용 Python

Shifter의 레지덴셜 및 ISP 프록시를 몇 분 안에 Python 스크립트에 통합하세요. requests, aiohttp, Scrapy, Selenium 및 모든 주요 Python HTTP 라이브러리와 원활하게 작동합니다.

빠른 시작

설치

pip install requests

기본 사용법

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

기능

requests, aiohttp, httpx, urllib3를 포함한 모든 Python HTTP 라이브러리와 함께 작동합니다
요청당, 세션당(sid), 또는 구성 가능한 스티키 세션(ttl)을 통한 자동 IP 로테이션
HTTP 및 SOCKS5 프록시 프로토콜 모두 완벽 지원
Python 3.7+ 및 Scrapy, BeautifulSoup 등 주요 스크레이핑 프레임워크와 호환
지오타겟팅 지원, 간단한 사용자 이름 매개변수를 통해 195개국 이상에서 프록시 선택
추가 SDK가 필요하지 않으며, 표준 프록시 환경 변수 또는 인라인 설정으로 Shifter를 구성할 수 있습니다

예시

기본 요청

Python에서 가장 인기 있는 HTTP 라이브러리와 함께 Shifter 프록시를 사용하는 가장 간단한 방법입니다. 사용자 이름에 국가, 지역, 도시 또는 ASN을 직접 설정하고 `sid`를 전달하여 요청 간에 동일한 IP를 유지하세요.

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

aiohttp + Sticky Sessions를 사용한 비동기

고성능 비동기 스크래핑을 위해 aiohttp를 사용하세요. 사용자 이름에 `sid-XXX`를 추가하면 요청 간에 동일한 IP를 유지할 수 있고, `ttl-N`을 추가하면 N초 동안 지속되는 타임드 스티키 세션을 사용할 수 있습니다.

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 미들웨어

Scrapy 스파이더에 커스텀 다운로더 미들웨어로 Shifter 프록시를 통합하세요. 사용자 이름에 `country-uk`, `region-bavaria`, `city-london`, `asn-7922`와 같은 선택자를 추가하여 지역을 타겟팅하고, `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

Selenium 브라우저 자동화를 Shifter 프록시를 통해 라우팅하세요. JavaScript로 렌더링된 페이지를 스크래핑하는 데 이상적입니다. 전체 브라우저 세션 동안 동일한 IP를 유지하려면 도시 수준 타겟팅을 `sid`와 결합하세요.

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()
자주 묻는 질문

자주 묻는 질문

Python와 Shifter 사용에 관한 일반적인 질문.

Shifter 프록시 URL을 사용하여 모든 requests 메서드에 proxies 딕셔너리를 전달하세요. 형식은 다음과 같습니다: 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"}. 그런 다음 requests.get(url, proxies=proxies)를 호출하세요.

예. Shifter 프록시는 aiohttp, httpx, Twisted를 비롯한 모든 비동기 Python HTTP 라이브러리와 함께 작동합니다. 라이브러리의 프록시 파라미터를 사용하여 프록시 URL을 전달하세요. aiohttp의 경우 session.get()에서 proxy 인자를 사용하고, httpx의 경우 Client 생성자에서 프록시를 설정하세요.

Shifter의 로테이팅 프록시 게이트웨이는 IP 로테이션을 자동으로 처리합니다. 기본적으로 요청마다 로테이션되거나, 세션 ID(sid) 또는 생존 시간(ttl)을 통해 제어할 수 있습니다. 추가 코드가 필요하지 않습니다.

예. request.meta['proxy']를 Shifter 프록시 URL로 설정하는 간단한 다운로더 미들웨어를 만들어 Shifter를 Scrapy와 통합할 수 있습니다. 이 미들웨어를 DOWNLOADER_MIDDLEWARES 설정에 추가하면 모든 Scrapy 요청이 자동으로 Shifter의 레지덴셜 프록시를 통해 라우팅됩니다.

예. Selenium의 Chrome 또는 Firefox WebDriver가 브라우저 옵션을 통해 Shifter를 HTTP 프록시로 사용하도록 구성하세요. Chrome의 경우 ChromeOptions에서 --proxy-server 플래그를 사용합니다. 인증이 필요한 프록시의 경우 브라우저 확장 프로그램이나 wire 프로토콜을 사용해 자격 증명을 전달할 수 있습니다.

Shifter 프록시는 HTTP 프록시를 지원하는 모든 Python 버전에서 작동하며, 여기에는 Python 3.7 이상이 포함됩니다. 프록시는 HTTP 레벨에서 구성되므로 버전에 관계없이 모든 Python HTTP 라이브러리와 호환됩니다. 선호하는 HTTP 클라이언트 외에 별도의 SDK나 패키지가 필요하지 않습니다.

시작하기

Shifter 사용을 함께 시작하기 Python

Shifter의 205M+ 레지덴셜 프록시를 5분 이내에 Python 스크립트에 통합하세요. 유연한 IP 로테이션, 지역 타겟팅, 모든 주요 Python 라이브러리와의 완벽한 호환성을 제공합니다.

Shifter 무료로 체험하기몇 분 만에 설정. 언제든지 취소 가능.