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

PyScript代码运行异常仅加载无结果,请求技术协助

PyScript页面持续加载无法输出结果的排查与解决

问题现象

运行提供的PyScript代码时,页面始终处于加载状态,仅显示loading runtime, runtime created,Initializing components...,无法输出运行结果。

核心问题与解决方法

1. 本地文件读取权限限制

PyScript运行在浏览器沙箱环境中,无法直接访问本地文件系统路径(如C:/Users\Sudip\Downloads\flip.csv),这会导致代码阻塞或抛出权限异常。

  • 解决方式:
    • 将flip.csv文件放置在网页的同一目录下,使用相对路径读取:
      df = pd.read_csv("flip.csv")
      
    • 或者通过浏览器文件选择器让用户上传文件,结合PyScript的文件处理API实现读取。

2. 依赖包名称错误

py-env中声明的BeautifulSoup不是PyPI上的正确包名,实际包名为beautifulsoup4,错误的包名会导致依赖安装失败,卡住初始化流程。

  • 修改后的py-env:
    <py-env>
        - pandas
        - requests
        - beautifulsoup4
        - lxml
    </py-env>
    

3. 跨域请求限制

使用requests.get访问Flipkart的URL会触发浏览器的同源策略限制,导致请求被拦截,代码无法继续执行。

  • 解决方式:
    • 使用PyScript内置的fetchAPI替代requests,它适配浏览器的跨域规则:
      from pyodide.http import fetch
      async def transform(url, TrackingPrice):
          response = await fetch(url)
          html = await response.text()
          only_item_cells = strainer("div", attrs={"class": "_30jeq3 _16Jk6d"})
          soup = BeautifulSoup(html, 'lxml', parse_only=only_item_cells)
          # 后续处理逻辑...
      
    • 注意:需要将外层代码改为异步执行,在py-script中添加async关键字并调用:
      async def main():
          df = pd.read_csv("flip.csv")
          for i in range(len(df["URL"])):
              await transform(df["URL"][i], df["TrackingPrice"][i])
      
      await main()
      

4. 缺少lxml解析器依赖

代码中使用lxml作为BeautifulSoup的解析器,但未在py-env中声明该依赖,会导致解析失败抛出异常,终止代码运行。

  • 已在上述修改后的py-env中添加lxml依赖。

修改后的完整代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>it's me</title>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    <py-env>
        - pandas
        - requests
        - beautifulsoup4
        - lxml
    </py-env>
</head>
<body>
    <py-script>
        import pandas as pd
        from bs4 import BeautifulSoup
        from bs4 import SoupStrainer as strainer
        from pyodide.http import fetch

        async def transform(url, TrackingPrice):
            response = await fetch(url)
            html = await response.text()
            only_item_cells = strainer("div", attrs={"class": "_30jeq3 _16Jk6d"})
            soup = BeautifulSoup(html, 'lxml', parse_only=only_item_cells)
            ajay = soup.text
            price = ajay.replace("₹", "").replace(",", "")
            print(price, TrackingPrice)

        async def main():
            # 确保flip.csv与网页在同一目录下
            df = pd.read_csv("flip.csv")
            for i in range(len(df["URL"])):
                await transform(df["URL"][i], df["TrackingPrice"][i])

        await main()
    </py-script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:50:21