首页 / 用例 / Scrapy
Scrapy 免费代理
Scrapy 通过 request.meta['proxy'] 内置代理支持。配合一个免费、每小时验证的列表和一个小巧的轮换中间件,就能把请求分散到许多 IP。
轮换代理中间件
把下面的中间件放进项目并在 settings.py 里启用。它加载一次验证列表,为每个请求随机分配代理,代理出错时重试另一个。
# middlewares.py
import random, requests
class VerifiedProxyMiddleware:
LIST = "https://raw.githubusercontent.com/xyzs996/free-proxy-health-list/main/proxies/protocols/http/data.txt"
def __init__(self):
txt = requests.get(self.LIST, timeout=15).text
self.proxies = [f"http://{l.strip()}" for l in txt.splitlines() if l.strip()]
def process_request(self, request, spider):
request.meta["proxy"] = random.choice(self.proxies)
def process_exception(self, request, exception, spider):
request.meta["proxy"] = random.choice(self.proxies)
return request # 用不同代理重试
settings.py
# settings.py
DOWNLOADER_MIDDLEWARES = {
"myproject.middlewares.VerifiedProxyMiddleware": 350,
"scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware": 400,
}
RETRY_ENABLED = True
RETRY_TIMES = 5
DOWNLOAD_TIMEOUT = 15
CONCURRENT_REQUESTS = 16
DOWNLOAD_DELAY = 1.0 # 有礼貌一点
小贴士
免费代理不稳定,请开启 RETRY_ENABLED 并给足 RETRY_TIMES。从 fast 子集起步命中率更高,长时间爬取之间重新加载列表(它每小时刷新)。始终遵守目标站的 robots.txt 和条款。
常见问题
怎么在 Scrapy 里设一个代理?
设置 request.meta['proxy'] = 'http://host:port',或导出 http_proxy。Scrapy 内置的 HttpProxyMiddleware 两者都识别。
Scrapy 能用 SOCKS5 吗?
Scrapy 默认中间件处理 HTTP 代理;SOCKS 需要第三方下载处理器。用 HTTP 列表的代理最省事。
列表从哪来?
从 CDN 下载 TXT 或 JSON 格式的验证列表。它每小时重新检测并发布,按速度从快到慢排序。