Free Proxy Health List

实时快照 · 3,287 proxies

Scrapy 代理中间件

即插即用的下载器中间件,每个请求轮换代理,失败时自动重试。

Scrapy 代理中间件

1. middlewares.py

import itertools, random

class RotatingProxyMiddleware:
    def __init__(self):
        with open("proxies.txt") as handle:
            self.proxies = [line.strip() for line in handle if line.strip()]
        random.shuffle(self.proxies)
        self.pool = itertools.cycle(self.proxies)

    def process_request(self, request, spider):
        request.meta["proxy"] = f"http://{next(self.pool)}"

2. settings.py

DOWNLOADER_MIDDLEWARES = {
    "myproject.middlewares.RotatingProxyMiddleware": 350,
    "scrapy.downloadermiddlewares.retry.RetryMiddleware": 550,
}
RETRY_TIMES = 5
DOWNLOAD_TIMEOUT = 10

能帮你省时间的说明

顺序很重要:代理中间件必须排在重试中间件之前,这样每次重试才会选到新的代理,而不是重复那个已经失败的。把 DOWNLOAD_TIMEOUT 设低 —— 免费代理是整条流水线里最慢的一环 —— 并调高 RETRY_TIMES 来吸收失败率。

相关教程

公开快照的使用边界
免费公共代理由不明身份的第三方运营且被多人共享,切勿通过它们传输密码、令牌或个人数据。请遵守 GitHub 可接受使用政策:不得用于垃圾信息、攻击、绕过访问控制,或违反网站政策的采集行为。