Pythonでプロキシを使用する理由
Pythonはデータ抽出の風景を支配します。 図書館のような リクエスト, ツイートと スクレイピー HTTP 呼び出しをトリガーします。, プロキシなし, スクリプトは、数分で IP 禁止をヒット. 使用方法 Pythonのプロキシ IPアドレスを回転させ、地理的な制限を回避し、スクラップ操作を確実にスケールアップできます。
このガイドでは、プロキシをPythonに統合する方法を学びます。 ProxyHatのPython SDK そして標準 requests ライブラリ。 各セクションには、すぐに実行できるコピーペーストリーコードが含まれています。
あなたが構築しているかどうか ウェブスクレイピングパイプライン、監視 SERP結果、または価格データの収集、このガイドは、認証、プロキシの回転、ジオターゲティング、エラー処理、および生産スケーリングをカバーしています。
インストールとセットアップ
ProxyHat SDK のインストールとリクエスト
ProxyHat Python SDK と、 requests pip を使用してライブラリ:
pip install proxyhat requests非同期ワークフローの場合、インストール httpx そして、 aiohttp: : :
pip install httpx aiohttpAPI 認証情報の取得
サインアップ プロキシハート API キーをダッシュボードから取得します。 お問い合わせ パスワード そして、 パスワード プロキシ認証(または API キー) 完全な認証の細部はで利用できます ProxyHat API ドキュメント. .
認証と基本構成
ProxyHat SDK の使用
SDK は、認証、回転、接続管理を処理します。
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")リクエストで未加工プロキシ認証を使用する
ご利用希望の方は requests プロキシ URL を直接設定します。
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"}簡単な取得 プロキシリクエスト
ここでは、ProxyHat 住宅プロキシを介して GET リクエストを送信する完全な例です。
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}")または標準と requests ライブラリ:
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])適切なプロキシタイプを選択する
ProxyHat は 3 つのプロキシタイプを提供しています。 ご使用のユースケースからお選びいただけます。 より深い比較については、ガイドをお読みください 住宅対データセンター対モバイルプロキシ. .
| タイプ: | 最高ののための | スピード | 検出リスク | コスト |
|---|---|---|---|---|
| 賃貸住宅 | ウェブスクレイピング、SERPトラッキング | メディア | 非常に低い | GB単位 |
| データセンター | 大容量、スピードクリティカルなタスク | ツイート | ハイアー | IP/月ごとの |
| モバイル | ソーシャルメディア、アプリのテスト | メディア | 最安値 | GB単位 |
コードのプロキシタイプを切り替える
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"
)回転対粘着セッション
回転プロキシ リクエストごとに新しいIPを割り当て、最大の匿名性が必要な大規模スクレイピングに最適です。 スティッキーセッション 同じ IP をセット期間保持し、ログインシーケンスやパジネーションナビゲーションなどの複数のステップのワークフローに不可欠です。
回転プロキシ(新しいIP各リクエスト)
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スティッキーセッション(サメIP for デュレーション)
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ジオターゲットリクエスト
特定の国からデータが必要な場合 ProxyHat サポート 195以上の場所でジオターゲティング. これは、ローカライズされたSERPスクレイピング、価格監視、コンテンツ検証に不可欠です。
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}")エラー処理と復元
ネットワークリクエストは失敗します。 プロキシタイムアウト。 ターゲットブロック 強力なエラー処理は、おもちゃスクリプトから生産スクレーパーを分離します。
基本リトライロジック
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 の組み込みリトリーの利用
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)通ることとの同時スクレーピング
順次リクエストが遅くなります。 プロダクションワークロードでは、Python の concurrent.futures プロキシによるリクエストの並列化
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 と 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")人気のPythonライブラリとの統合
リクエスト(セッション)での利用
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 の使用
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での使用
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())Scrapyで使う
ProxyHat を Scrapy のスパイダーに追加します。 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(),
}生産のヒント
接続プールとタイムアウト
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)ログおよび監視
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環境 認証のための変数
資格情報をハードコードしません。 環境変数を使用する:
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"
)利用可能なプロキシプランとトラフィックオプションの完全なリストについては、 プライシングページ. 高度なユースケースとエンドポイントリファレンスについては、 API ドキュメント。また私達のガイドを探検できます 2026年にWebスクレイピングに最適なプロキシ プロバイダーの比較。
キーテイクアウト
- 1つのコマンドにインストールします。
pip install proxyhat requestsすぐに始めよう。- シンプルさのためにSDKを使用する: ProxyHat Python SDK は、認証、レトリー、および自動回転を処理します。
- 適切なプロキシタイプを選択してください: スクラップ、スピードのためのデータセンター、ソーシャルプラットフォーム向けのモバイル。
- 回転対棒: バルクスクレーピング、マルチステップワークフロー用のスティッキーセッション用の回転プロキシを使用します。
- 必要に応じてジオターゲット: ローカルデータ収集のための国と都市を指定します。
- エラーを適切に処理します。 生産の信頼性のための指数関数的なバックオフおよび試行の論理を実行して下さい。
- 通貨でスケール: 使用条件
ThreadPoolExecutorまたはasyncioリクエストを並列化します。- 決してハードコードの資格情報: 環境変数に API キーを保存します。
よくある質問
Pythonリクエストでプロキシを設定するにはどうすればよいですか?
パス proxies 任意の requests メソッド: requests.get(url, proxies={"http": "http://user:pass@host:port", "https": "http://user:pass@host:port"}). ProxyHat SDK は、プロキシ設定を内部で処理することで、これをさらに簡素化します。
Pythonの回転と粘りのあるプロキシの違いは何ですか?
プロキシを回転させると、大規模なスクレイピングに理想的であるすべての要求に対して新しいIPアドレスを割り当てます。 スティッキープロキシは、ログインセッション、ショッピングカート、またはIPの一貫性が重要である閲覧に必要なセット期間(例えば、10-30分)と同じIPを維持します。
asyncioとaiohttpでProxyHatプロキシを使うことはできますか?
はい。 ProxyHat プロキシは、プロキシ設定をサポートする HTTP クライアントと連携します。 aiohttp, httpx (非同期モード) asyncio-ベースフレームワーク。 プロキシ URL をプロキシ URL に渡す proxy async クライアントのパラメーター。
Pythonでプロキシエラーとタイムアウトを処理する方法は?
リクエストをトライ/ブロックキャッチを除く ProxyError, Timeoutと ConnectionError. 指数関数のバックオフ(レトリー間の2倍の待ち時間)を実行し、最大リトライ数を設定します。 ProxyHat SDK は、コンフィギュラ可能なパラメータで組み込みのリトライロジックが含まれています。
PythonライブラリがプロキシでWebスクレイピングに最適なのは?
簡単なタスクのために、 requests ProxyHat SDK は最も簡単なオプションです。 高通貨非同期スクレーピングのために、使用 httpx または aiohttp. 下記のリンクおよびデータ抽出と複雑なクロールのために、 Scrapy プロキシミドルウェアは、最も強力な選択肢です。 ProxyHat プロキシとシームレスに動作します。






