本文详解 pyscript 项目中调用 yandex 天气 api 时页面无输出的问题根源,并提供使用 display() 替代 print()、修复异步请求与 json 解析错误的完整解决方案。
本文详解 pyscript 项目中调用 yandex 天气 api 时页面无输出的问题根源,并提供使用 display() 替代 print()、修复异步请求与 json 解析错误的完整解决方案。
在 PyScript 中,print() 函数的行为已发生重要变化:自版本 2023.11.1 起,print() 默认仅输出到浏览器开发者控制台(Console),不会渲染到网页 DOM 中。这正是您页面为空的根本原因——尽管请求成功、逻辑无报错,但结果未被展示。
此外,原代码中还存在两处关键错误:
以下是修正后的完整可运行示例(兼容 PyScript ≥ 2024.1.1):
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>莫斯科天气预报</title> <script defer src="https://pyscript.net/releases/2024.1.1/pyscript.js"></script> <link rel="stylesheet" href="https://pyscript.net/releases/2024.1.1/pyscript.css"/></head><body> <div id="weather-output"></div> <py-script> import pyodide import asyncio API_KEY = '8e4cf478-53b6-45bc-8597-9946db9f1fd5' url = 'https://api.weather.yandex.ru/v2/forecast' params = { 'lat': 55.753215, 'lon': 37.622504, 'lang': 'ru_RU' } headers = { 'X-Yandex-API-Key': API_KEY } async def get_weather(): try: # 正确发起带参数和头信息的 GET 请求 response = await pyodide.http.pyfetch( url, method="GET", headers=headers, params=params ) data = await response.json() # ✅ 唯一且正确的 await 解析 fact = data.get('fact', {}) temperature = fact.get('temp', '未知') condition = fact.get('condition', '未知') # ✅ 使用 display() 将内容输出到页面(自动追加到 <py-script> 标签位置) # 若需指定容器,可传入 target 参数(如 target="weather-output") display(f"?️ 莫斯科实时天气:{temperature}°C,{condition}") except Exception as e: display(f"❌ 获取天气失败:{e}") # ✅ 使用 asyncio.create_task() 或直接 await(PyScript 支持顶层 await) await get_weather() </py-script></body></html>
✅ 关键改进说明:
⚠️ 注意事项:
通过以上调整,您的天气预报将清晰、稳定地呈现在网页上,而非仅藏于控制台。