如何通过解析URL获取HTML页面内script标签中的JSON数据
实现方案(Python版本)
首先安装所需依赖:
pip install requests beautifulsoup4
完整代码示例
import requests from bs4 import BeautifulSoup import json def get_json_from_script(url: str) -> dict: # 1. 请求URL获取HTML内容 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } response = requests.get(url, headers=headers) response.raise_for_status() # 请求失败直接抛出异常 # 2. 解析HTML提取目标script标签内容 soup = BeautifulSoup(response.text, "html.parser") target_script = soup.find("script", id="something", type="application/json") if not target_script: raise ValueError("未找到符合要求的script标签") # 3. 转换为标准JSON对象 try: json_data = json.loads(target_script.text.strip()) except json.JSONDecodeError: raise ValueError("script标签内的内容不符合JSON格式规范") return json_data # 调用示例 if __name__ == "__main__": target_url = "你的目标URL" result = get_json_from_script(target_url) # 打印格式化的JSON字符串 print(json.dumps(result, indent=2, ensure_ascii=False))
注意事项
- 如果目标页面是前端动态渲染的,初始返回的HTML中不存在对应script标签,需要换成Selenium、Playwright这类支持浏览器渲染的工具获取完整页面内容后再解析。
- 可以根据实际的script标签id和type调整
find方法的筛选参数,适配不同站点的结构。
内容的提问来源于stack exchange,提问作者Mert Karagöz
相关产品推荐
相关产品推荐

