ProxyForge Download

Build a Proxy Checker in Python: Validate, Score, and Filter Working Proxies

Introduction

Proxy checking is a crucial step for developers working with web scraping and automation. Proxies help in bypassing IP bans, accessing geo-restricted content, and ensuring anonymity. However, not all proxies are created equal, and many can be dead or slow, leading to inefficient and unreliable operations.

In this guide, we'll build a practical proxy checker in Python that validates proxies concurrently using asyncio and aiohttp, measures latency, detects anonymity levels (transparent vs elite), handles timeouts, filters out dead proxies, and exports the results to a file or database. We’ll also compare our approach with paid proxy health APIs like Bright Data's health endpoint.

Setting Up the Environment

Before diving into the code, ensure you have Python installed on your system. You will need the following libraries:

pip install aiohttp asyncio

We'll use aiohttp for asynchronous HTTP requests and asyncio for concurrency management.

Proxy Validation with Concurrency

Let's start by writing a function to validate proxies concurrently using asyncio.

import asyncio
import aiohttp

async def check_proxy(proxy):
    url = "https://httpbin.org/ip"
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(url, proxy=f"http://{proxy}", timeout=10) as response:
                if response.status == 200:
                    return {"proxy": proxy, "status": "alive", "response_time": response.time}
        except (aiohttp.ClientError, asyncio.TimeoutError):
            return {"proxy": proxy, "status": "dead"}

async def validate_proxies(proxies):
    tasks = [check_proxy(proxy) for proxy in proxies]
    results = await asyncio.gather(*tasks)
    return [result for result in results if result]

# Example usage
proxies = [
    "192.0.2.1:8080",
    "192.0.2.2:3128",
    "192.0.2.3:80"
]
loop = asyncio.get_event_loop()
alive_proxies = loop.run_until_complete(validate_proxies(proxies))
print(alive_proxies)

Explanation

Measuring Latency

The above code already includes latency measurement as part of the response object returned by aiohttp. You can access it using response.time.

# Example output format
{
    "proxy": "192.0.2.1:8080",
    "status": "alive",
    "response_time": 0.456789  # in seconds
}

Detecting Anonymity Levels

Anonymity detection is crucial for understanding how proxies handle your requests. We'll check if the proxy is transparent (reveals your IP) or elite (hides it).

async def check_anonymity(proxy):
    url = "https://httpbin.org/ip"
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(url, proxy=f"http://{proxy}", timeout=10) as response:
                if response.status == 200:
                    ip_info = await response.json()
                    client_ip = ip_info.get('origin')
                    # If the client IP is different from the proxy IP, it's elite
                    return {
                        "proxy": proxy,
                        "status": "alive",
                        "response_time": response.time,
                        "anonymity": "elite" if client_ip != proxy.split(':')[0] else "transparent"
                    }
        except (aiohttp.ClientError, asyncio.TimeoutError):
            return {"proxy": proxy, "status": "dead"}

async def validate_proxies_with_anonymity(proxies):
    tasks = [check_anonymity(proxy) for proxy in proxies]
    results = await asyncio.gather(*tasks)
    return [result for result in results if result]

# Example usage
alive_proxies_with_anonymity = loop.run_until_complete(validate_proxies_with_anonymity(proxies))
print(alive_proxies_with_anonymity)

Explanation

Handling Timeouts and Exceptions

Timeouts and exceptions are handled within the try-except block inside the check_proxy function. If a request fails due to a timeout or client error, the proxy is marked as "dead".

Filtering Dead Proxies

The filtering of dead proxies is already handled in the list comprehension that creates the final results list:

return [result for result in results if result]

This line ensures only proxies with valid results (i.e., not None) are included in the output.

Exporting Results to File or Database

You can export the proxy check results to a file or database using standard Python libraries.

To File

import json

def save_to_file(results, filename):
    with open(filename, 'w') as f:
        json.dump(results, f)

# Example usage
save_to_file(alive_proxies_with_anonymity, "proxies.json")

To Database (using SQLite for simplicity)

import sqlite3

def save_to_db(results, db_name):
    conn = sqlite3.connect(db_name)
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS proxies
                 (proxy TEXT, status TEXT, response_time REAL, anonymity TEXT)''')
    c.executemany('INSERT INTO proxies VALUES (?, ?, ?, ?)', [(p['proxy'], p['status'], p['response_time'], p['anonymity']) for p in results])
    conn.commit()
    conn.close()

# Example usage
save_to_db(alive_proxies_with_anonymity, "proxies.db")

Comparing with Paid Proxy Health APIs

Paid services like Bright Data offer robust proxy health endpoints that provide detailed information about proxies, including their reliability and performance. While our Python script provides basic validation and scoring, these paid services can be more reliable for production use.

For example, Bright Data's health endpoint might look something like this:

async def check_proxy_with_paid_service(proxy):
    url = f"https://api.brightdata.com/proxy/health?proxy={proxy}"
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(url, timeout=10) as response:
                if response.status == 200:
                    data = await response.json()
                    return {
                        "proxy": proxy,
                        "status": data['status'],
                        "response_time": data['response_time'],
                        "anonymity": data['anonymity']
                    }
        except (aiohttp.ClientError, asyncio.TimeoutError):
            return {"proxy": proxy, "status": "dead"}

# Usage similar to previous functions

Conclusion

Building a proxy checker in Python using asyncio and aiohttp is an efficient way to validate proxies at scale. This approach allows you to measure latency, detect anonymity levels, handle timeouts, filter dead proxies, and export results easily.

While this solution provides basic validation, professional or managed proxy services like Bright Data and SmartProxy offer advanced features that are essential for reliable web scraping and automation tasks in production environments.

If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download

Free proxies break. ProxyForge doesn't.

The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.

Download ProxyForge free →