求助:PyScript跨域获取网站数据对接JS及模块导入错误解决
问题与解决建议
问题背景
本人对Python并不熟悉,编写了一段Python脚本(如下),通过requests和BeautifulSoup抓取指定ID对应的目标网站数据并保存为JSON文件。由于JavaScript的fetch受CORS同源策略限制,且不想搭建代理服务器,原本在网站上设置了文件上传功能让用户上传脚本生成的文件,之后想到可以用PyScript在网页中运行该脚本,但遇到了模块导入错误。需求是让用户输入ID后,获取对应网站数据并汇总为JSON对象,再传递给JavaScript做后续处理,希望得到相关解决建议。
原Python脚本
import sys import json import requests from bs4 import BeautifulSoup # Declare variables review_limit = 15 comment_limit = 4 # Get the list of id numbers from the command line arguments ids = sys.argv[1:] # If no id numbers are provided, ask the user to enter them if not ids: ids = input("Enter the id numbers separated by a space: ").split() # Initialize the data object data = {} for id in ids: # Make sure it's a valid number if id and int(id) > 0: url_model = f"https://example.com/{id}/{review_limit}/{comment_limit}/" # Send a GET request to the page and parse the response response = requests.get(url_model) doc = BeautifulSoup(response.text, "html.parser") # Extract the data from the response page_data = doc.find(id="jsonDiv").text # Parse the data text as JSON page_data = json.loads(page_data) # Add the data to the data object data[id] = { "pageData": page_data } # Write the data object to a file, pretty-printing the JSON data with open("data.json", "w") as outfile: json.dump(data, outfile, indent=2)
解决建议
1. 修复PyScript模块导入错误
PyScript需要显式声明要加载的第三方Python包,在HTML中通过<py-env>标签指定依赖:
<py-env> - requests - beautifulsoup4 </py-env>
配置后PyScript会自动下载并加载这两个包,解决导入失败问题。
2. 适配网页环境修改脚本
原脚本依赖命令行参数和本地输入,需替换为网页交互逻辑:
- 移除
sys.argv相关代码,改用HTML输入框获取用户ID - 替换
input()函数,通过JS传递输入框内容给Python - 删除本地文件写入代码,改为将JSON数据直接传递给JavaScript
修改后的PyScript代码示例:
import json import requests from bs4 import BeautifulSoup from js import document, window review_limit = 15 comment_limit = 4 def fetch_data(): # 获取输入框中的ID(假设输入框id为"id-input") input_element = document.getElementById("id-input") ids = input_element.value.strip().split() data = {} for id in ids: try: id_num = int(id) if id_num <= 0: continue url_model = f"https://example.com/{id_num}/{review_limit}/{comment_limit}/" response = requests.get(url_model) response.raise_for_status() # 捕获请求错误 doc = BeautifulSoup(response.text, "html.parser") page_data_text = doc.find(id="jsonDiv").text page_data = json.loads(page_data_text) data[id] = {"pageData": page_data} except Exception as e: # 提示用户错误信息 window.alert(f"处理ID {id}时出错: {str(e)}") continue # 将数据转为JSON字符串,传递给JS处理函数 window.handleData(json.dumps(data))
3. 搭建HTML交互结构
在HTML中添加输入框、按钮,整合PyScript和JavaScript逻辑:
<input type="text" id="id-input" placeholder="输入ID,用空格分隔"> <button onclick="runPython()">获取数据</button> <py-env> - requests - beautifulsoup4 </py-env> <py-script> # 上面修改后的Python代码 </py-script> <script> function runPython() { // 调用PyScript中的fetch_data函数 pyscript.interpreter.globals.get('fetch_data')(); } function handleData(jsonStr) { // 处理从Python传来的JSON数据 const data = JSON.parse(jsonStr); // 此处编写后续JS逻辑,比如渲染数据、存储等 console.log("获取到的数据:", data); } </script>
4. 注意CORS限制
PyScript的requests底层仍依赖浏览器fetch API,因此同样受CORS策略限制。如果目标网站未配置允许当前域名的跨域请求,即使使用PyScript也会报错。这种情况下可尝试:
- 检查目标网站是否提供支持CORS的官方API
- 查找目标网站是否有JSONP接口可用
- 若以上都不可行,搭建简易代理服务器仍是备选方案
内容的提问来源于stack exchange,提问作者Curtis
相关产品推荐
相关产品推荐

