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

Python使用requests库下载指定URL图片失败 无需WebDriver如何解决

解决requests无法下载指定站点图片的方案

1kb无效文件的本质是目标站点配置了基础反爬虫校验:无有效请求头的裸请求会被返回HTML类型的校验响应,只有符合浏览器特征的请求才能拿到真实图片资源,对应观察到的「两次请求、第一次返回text/html第二次返回image/jpg」的现象。

方案1:使用requests.Session适配多轮校验逻辑

Session会自动留存请求间的Cookie、跟进重定向,完美适配这类需要先过校验的场景,无需启动WebDriver:

import requests
import shutil

image_url = "https://www.metmuseum.org/-/media/images/visit/met-fifth-avenue/fifthave_teaser.jpg"
# 模拟浏览器的请求头,核心是携带合法User-Agent
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
}

# 初始化Session自动管理Cookie和重定向
with requests.Session() as session:
    response = session.get(image_url, headers=headers, stream=True)
    # 先校验返回的确实是图片类型再写入,避免存储无效内容
    if response.headers.get("content-type") in ["image/jpeg", "image/jpg"]:
        response.raw.decode_content = True
        with open("image1.jpg", "wb") as file:
            shutil.copyfileobj(response.raw, file)
        print("图片下载成功")
    else:
        print(f"返回非图片资源,类型为:{response.headers.get('content-type')}")

方案2:urllib版本适配

原有urllib方案仅需要补充请求头参数即可正常使用:

import urllib.request

image_url = "https://www.metmuseum.org/-/media/images/visit/met-fifth-avenue/fifthave_teaser.jpg"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
}

req = urllib.request.Request(image_url, headers=headers)
with urllib.request.urlopen(req) as response, open("image1.jpg", "wb") as out_file:
    out_file.write(response.read())
  • User-Agent可根据实际使用环境替换,不需要和示例完全一致
  • 后续遇到同类站点下载失败的情况,可优先排查是否需要添加referer、cookie等额外请求头参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 23:06:07