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

Python3.7下requests获取图片报403,Python3.11正常的解决办法

解决Python 3.7中requests下载图片返回403的问题

1. 模拟完整浏览器请求头(最常见修复方案)

目标网站大概率通过User-Agent字段拦截非浏览器请求,Python 3.11与3.7的requests默认UA存在差异,直接添加标准浏览器UA即可尝试绕过:

import requests

url = "你的目标图片URL"
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
    'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.9'
}

response = requests.get(url, headers=headers)
response.raise_for_status()
with open('target_image.jpg', 'wb') as f:
    f.write(response.content)

2. 强制使用高版本TLS协议

Python 3.7默认的TLS版本较低,部分网站已禁用旧版TLS,可手动指定TLS 1.2或1.3:

import requests
import ssl
from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager
from urllib3.util.ssl_ import create_urllib3_context

class TLSAdapter(HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        # 指定TLS版本,可替换为ssl.PROTOCOL_TLSv1_3尝试
        context = create_urllib3_context(ssl_version=ssl.PROTOCOL_TLSv1_2)
        kwargs['ssl_context'] = context
        return super().init_poolmanager(*args, **kwargs)

url = "你的目标图片URL"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'}

session = requests.Session()
session.mount('https://', TLSAdapter())
response = session.get(url, headers=headers)
response.raise_for_status()
with open('target_image.jpg', 'wb') as f:
    f.write(response.content)

3. 携带验证Cookie(针对需登录/会话验证的网站)

若目标图片需要特定会话才能访问,可在浏览器打开图片URL后,复制请求头中的Cookie字段加入请求:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
    'Cookie': '此处粘贴浏览器中复制的Cookie内容'
}

注意Cookie存在有效期,过期后需重新获取。

4. 手动处理重定向

部分网站的重定向逻辑在Python 3.7环境下会触发403,可禁用自动重定向后手动跟进:

response = requests.get(url, headers=headers, allow_redirects=False)
if response.status_code == 302:
    redirect_url = response.headers['Location']
    response = requests.get(redirect_url, headers=headers)
response.raise_for_status()
with open('target_image.jpg', 'wb') as f:
    f.write(response.content)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:32:49