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

Python requests请求报SSL模块不可用导致HTTPS连接失败如何解决

解决方案

原因说明

你写的请求地址是HTTP协议,但服务端会自动重定向到HTTPS协议地址,报错核心是你的Windows环境下Python自带的SSL模块不可用,和requests、pyOpenSSL的第三方包版本无关。

修复步骤

1. 临时验证重定向逻辑

先修改代码关闭自动重定向,确认跳转逻辑正常:

import requests
from bs4 import BeautifulSoup

url = 'http://pythondojang.bitbucket.io/weather/observation/currentweather.html'
response =  requests.get(url, verify=False, allow_redirects=False)
print(response.status_code)
print(response.headers.get('Location'))

如果输出301/302状态码,以及HTTPS开头的跳转地址,说明问题出在本地Python SSL模块。

2. 修复Python SSL模块

Windows下Python缺失SSL模块基本是因为安装包不完整导致,按以下操作:

  • 卸载当前安装的Python 3.8.8
  • 下载Python官方对应版本的完整安装包,安装时勾选Add Python to PATH、Install for all users,可选功能中务必勾选SSL/TLS相关组件
  • 安装完成后打开命令行执行 python -c "import ssl; print(ssl.OPENSSL_VERSION)",如果能正常输出OpenSSL版本号即说明SSL模块修复完成
  • 重新安装项目依赖:
pip install requests==2.26.0 beautifulsoup4 pyOpenSSL==21.0.0

3. 验证修复效果

重新运行原始代码即可正常获取页面内容。如果仍有SSL报错,可以使用自定义SSL适配器兼容:

import requests
import ssl
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager

class SSLAdapter(HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        context = ssl.create_default_context()
        context.check_hostname = False
        context.set_ciphers('DEFAULT:@SECLEVEL=1')
        kwargs['ssl_context'] = context
        return super(SSLAdapter, self).init_poolmanager(*args, **kwargs)

url = 'http://pythondojang.bitbucket.io/weather/observation/currentweather.html'
session = requests.Session()
session.mount('https://', SSLAdapter())
response = session.get(url, verify=False)
soup= BeautifulSoup(response.content, 'html.parser')
print(soup)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:06:06