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

PyScript开发天气网站遇requests模块找不到错误的解决求助

解决PyScript中ModuleNotFoundError: No module named 'requests'的问题

问题根源

PyScript运行在浏览器内置的Pyodide Python环境中,和你本地cmd里安装的Python完全是两个独立环境——你在本地装的requests根本不会被浏览器的PyScript调用,所以才会报错。

解决方法一:用<py-config>声明依赖

PyScript需要通过专门的配置标签来加载第三方包,步骤如下:

  1. 在HTML的<head>标签内添加<py-config>标签,声明要安装的requests包
  2. 确保配置使用TOML格式,指定packages列表

修改后的HTML代码:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天气查询网站</title>

    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    
    <!-- 添加PyScript配置,声明需要的包 -->
    <py-config>
        packages = ["requests"]
    </py-config>
</head>
<body>
    <py-script src="main.py"></py-script>
    <input id="getweather" placeholder="搜索城市天气...">
    <button id="btngwt" pys-onClick="play_game">查询天气</button>
    <h1 id="babo"></h1>
    
</body>
</html>

这样PyScript会自动在浏览器环境中安装并加载requests模块,你的原有Python代码不需要改动。

解决方法二:使用PyScript内置的pyfetch替代requests

Pyodide自带了pyfetch(类似JavaScript的fetch),可以直接用来发送HTTP请求,不需要额外安装包。修改你的Python代码如下:

import json
from pyodide.http import pyfetch

search = Element("getweather")
something = Element("babo")

async def play_game(*args):
    wt = search.value
    city = wt # 도시 
    apiKey = "db1e8e28d93cbbabad4f0162fa37dbdf"
    lang = 'kr' # 언어
    units = 'metric' # 화씨 온도를 섭씨 온도로 변경
    api = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={apiKey}&lang={lang}&units={units}"

    # 使用pyfetch发送请求,注意需要await
    response = await pyfetch(api)
    result = await response.json()

    something.element.innerText = f"{result}"

注意:pyfetch是异步方法,所以需要把play_game改成异步函数(加async),并在调用pyfetch和response.json()时加await。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:45:32