Back to Blog

دليل استخدام البروكسي مع مكتبة Python Requests

عند بناء أدوات جمع البيانات (Web Scraping)، تعتبر مكتبة requests في Python هي الخيار الأول لسهولتها. لكن بمجرد أن تبدأ في إرسال آلاف الطلبات، ستحتاج لإدارة البروكسيات بذكاء لضمان استمرارية العمل.

الإعداد الأساسي (Basic Configuration)

يمكنك تمرير قاموس (Dictionary) يحتوي على إعدادات البروكسي لبروتوكولي HTTP و HTTPS.


import requests

proxies = {
    "http": "http://user:pass@10.10.1.10:3128",
    "https": "http://user:pass@10.10.1.10:1080",
}

try:
    response = requests.get("https://api.ipify.org?format=json", proxies=proxies, timeout=5)
    print(response.json())
except requests.exceptions.ProxyError:
    print("فشل الاتصال بالبروكسي")
                    

تدوير البروكسي (Proxy Rotation)

للاستفادة القصوى، لا تستخدم بروكسي واحد لكل الطلبات. قم بإنشاء قائمة (List) وقم باختيار بروكسي عشوائي لكل طلب.


import random
import requests

proxy_list = [
    "http://ip1:port",
    "http://ip2:port",
    "http://ip3:port"
]

for i in range(10):
    proxy = {"http": random.choice(proxy_list), "https": random.choice(proxy_list)}
    try:
        r = requests.get("https://site.com", proxies=proxy)
        print(f"Request {i} success")
    except:
        print(f"Request {i} failed, trying another proxy...")
                    

جلسات (Sessions) والبروكسي

إذا كنت تستخدم requests.Session() للحفاظ على الكوكيز، يمكنك ضبط البروكسي للجلسة بأكملها مرة واحدة: session.proxies.update(proxies). هذا مفيد جداً عند التعامل مع المواقع التي تتطلب تسجيل دخول.

Disclosure: we may earn a commission if you purchase through some links.

Services Related To This Article

These offers are related to privacy, password security, and development workflows. Replace the current links with your real affiliate links through environment variables.

Default Links Need Replacement

Proton

Privacy, mail, and VPN

A strong fit for privacy-focused visitors who want VPN and secure email under one brand.

Explore Proton

Surfshark

Consumer VPN

Best on pages about geo-blocking, privacy, and public Wi-Fi protection.

Try Surfshark

NordVPN

High-converting VPN

A clear offer for users who need a paid, more durable alternative to a free proxy.

View NordVPN

1Password

Password management

The best match for password, secrets, team access, and personal security pages.

Discover 1Password

DigitalOcean

Developer cloud hosting

A strong fit for proxy setup, server, and infrastructure content aimed at developers and small teams.

Start with DigitalOcean