You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python requests获取Bright Data代理的x-brd-ip响应头

提取Bright Data代理的x-brd-ip响应头

Bright Data的x-brd-ip头返回在连接建立阶段,而非最终响应的头集合中,requests默认只会解析最终响应的头,因此需要通过自定义HTTP适配器来捕获这个早期返回的头。

解决方案:自定义HTTPAdapter捕获原始响应头

利用requests基于urllib3的特性,我们可以重写HTTPAdapter的build_response方法,从urllib3的原始响应对象中提取连接阶段的x-brd-ip头,并将其添加到requests响应的headers中。

代码实现

import requests
from requests.adapters import HTTPAdapter

class BrightDataIPAdapter(HTTPAdapter):
    def build_response(self, request, urllib3_response):
        # 构建基础requests响应
        response = super().build_response(request, urllib3_response)
        
        # 从urllib3的底层原始响应中提取x-brd-ip
        if hasattr(urllib3_response, '_original_response'):
            original_response = urllib3_response._original_response
            brd_ip = original_response.getheader('x-brd-ip')
            if brd_ip:
                response.headers['x-brd-ip'] = brd_ip
        
        return response

# 初始化Session并挂载自定义适配器
session = requests.Session()
session.mount('http://', BrightDataIPAdapter())
session.mount('https://', BrightDataIPAdapter())

# 配置Bright Data代理(替换为你的代理信息)
brightdata_proxy = "http://{your_username}:{your_password}@{your_zone}.brightdata.com:{port}"
session.proxies.update({
    "http": brightdata_proxy,
    "https": brightdata_proxy
})

# 发起请求并获取代理IP
resp = session.get("https://example.com")
print("使用的代理IP:", resp.headers.get("x-brd-ip"))

原理说明

  • urllib3的HTTPResponse对象包含一个_original_response属性,对应底层socket返回的原始响应,其中包含连接阶段Bright Data代理返回的所有头信息。
  • 通过重写build_response方法,我们可以捕获这个原始响应中的x-brd-ip,并将其注入到requests最终返回的Response的headers字典中,方便直接调用。

注意事项

  • 确保代理地址格式正确:Bright Data的代理通常格式为http://用户名:密码@区域标识.brightdata.com:端口
  • 若_original_response属性不存在,可检查urllib3版本(建议使用urllib3 1.26+版本)
  • 部分场景下需手动添加Expect: 100-continue请求头触发代理返回连接阶段头,可在请求时添加headers={"Expect": "100-continue"}

内容的提问来源于stack exchange,提问作者Chirag Goel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:12:44