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

使用PyScript在网页调用API遇http.client无HTTPSConnection属性错误

解决'http.client'没有属性'HTTPSConnection'的问题

问题背景

使用http.client调用API时,网页环境下报错'http.client' has no attribute 'HTTPSConnection',但相同代码在Jupyter Notebook中可正常运行。相关信息如下:

报错信息

AttributeError: module 'http.client' has no attribute 'HTTPSConnection'

原代码

import http.client

conn = http.client.HTTPSConnection("www.banxico.org.mx")
payload = ''
headers = {}
conn.request("GET", "/SieAPIRest/service/v1/series/SP68257/datos/2022-11-11/2022-11-11?token=04021aac739b77e232d9670147936836e9e9fc31e08bde26665c0f013df94471", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

原因分析

网页端的Python运行环境(如部分在线编辑器、Pyodide等)通常会对标准库进行裁剪或功能限制,http.client的HTTPS相关模块可能未被包含或启用,导致无法调用HTTPSConnection。

解决方案

根据不同网页环境,可选择以下方案:

方案1:使用环境原生HTTP工具(以Pyodide为例)

如果是浏览器端的Pyodide环境,可使用pyodide.http.fetch替代http.client,示例代码:

import pyodide.http

url = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SP68257/datos/2022-11-11/2022-11-11?token=04021aac739b77e232d9670147936836e9e9fc31e08bde26665c0f013df94471"
response = await pyodide.http.fetch(url)
data = await response.text()
print(data)

方案2:使用requests库(若环境允许安装)

如果网页环境支持安装第三方库,requests兼容性更好且代码更简洁:

# 若未安装requests,先执行安装命令(部分环境支持)
# !pip install requests

import requests

url = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SP68257/datos/2022-11-11/2022-11-11?token=04021aac739b77e232d9670147936836e9e9fc31e08bde26665c0f013df94471"
response = requests.get(url)
print(response.text)

方案3:检查环境网络权限

部分网页环境会限制外部网络请求,若上述方案仍失败,需确认环境是否允许访问目标API域名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:30:52