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

如何用Python WebDriver获取Chrome DevTools中图片的完整响应

绕过Cloudflare获取网页图片(Selenium + Chrome DevTools协议)

你当前的get_log("performance")只能拿到请求元数据,无法获取完整响应体。要实现类似Chrome DevTools"Copy response"的功能,需要直接调用Chrome DevTools协议(CDP)接口,以下是具体实现:

实现方案

利用Selenium的execute_cdp_cmd方法调用CDP的Network.getResponseBody接口,直接从浏览器会话中获取图片响应数据。

完整代码

from selenium import webdriver
import time
import base64

# 配置Chrome选项(复用已打开的调试浏览器)
options = webdriver.ChromeOptions()
options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

driver = webdriver.Chrome(options=options)

# 启用CDP网络监控,拦截图片请求
driver.execute_cdp_cmd('Network.enable', {})
driver.execute_cdp_cmd('Network.setRequestInterception', {
    'patterns': [{'resourceType': 'Image', 'interceptionStage': 'HeadersReceived'}]
})

image_request_ids = []

def intercept_request(request):
    # 放行请求,同时记录图片请求的requestId
    driver.execute_cdp_cmd('Network.continueInterceptedRequest', {'interceptionId': request['interceptionId']})
    if request['resourceType'] == 'Image':
        image_request_ids.append(request['requestId'])

# 绑定请求拦截回调
driver.request_interceptor = intercept_request

# 访问目标页面
target_url = "你的目标网页URL"
driver.get(target_url)
time.sleep(5)  # 等待页面完全加载

# 遍历图片请求,获取响应体并保存
for req_id in image_request_ids:
    try:
        # 获取图片响应体
        resp = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': req_id})
        # 解码响应数据
        image_data = base64.b64decode(resp['body']) if resp['base64Encoded'] else resp['body']
        
        # 从请求URL提取文件名
        req_details = driver.execute_cdp_cmd('Network.getRequestDetails', {'requestId': req_id})
        filename = req_details['request']['url'].split('/')[-1].split('?')[0]
        
        # 保存图片到本地
        with open(f'./{filename}', 'wb') as f:
            f.write(image_data)
        print(f"图片已保存: {filename}")
    except Exception as e:
        print(f"处理图片失败: {str(e)}")

driver.quit()

关键细节

  • CDP接口作用:Network.getResponseBody直接从浏览器的网络会话中拉取响应体,完全复用浏览器已通过Cloudflare验证的会话,不会触发403
  • 请求过滤:通过Network.setRequestInterception只拦截图片类型请求,减少不必要的资源处理
  • 编码处理:部分图片响应会以base64格式返回,需解码后再写入文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:49:58