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

如何用Beautiful Soup提取<script>中各函数的指定字符串?

提取HTML中多个JavaScript函数内容的解决方案

核心问题分析

Beautiful Soup仅负责解析HTML结构,无法识别JavaScript函数的语法边界,所以默认只能抓取到第一个匹配的answerQuiz()内容。要提取所有同类函数,必须结合正则表达式或JavaScript语法解析库来定位函数体。

方案一:正则表达式匹配(轻量高效)

步骤:

  • 用Beautiful Soup提取所有<script>标签内容
  • 用正则匹配所有以answerQuiz开头的函数定义
  • 从匹配到的函数体中提取Answer/Contents/Quiz相关字符串
from bs4 import BeautifulSoup
import re

# 假设html为你的目标HTML内容
soup = BeautifulSoup(html, 'html.parser')
script_tags = soup.find_all('script')

# 匹配所有answerQuizN()函数的正则(适配带数字后缀的函数名)
func_pattern = re.compile(r'function answerQuiz\d*\(\)\s*{([\s\S]*?)}')
# 匹配目标键值对的正则
target_pattern = re.compile(r'(Answer|Contents|Quiz)\s*[:=]\s*["\'](.*?)["\']')

for script in script_tags:
    if not script.string:
        continue
    # 提取所有匹配的函数体
    func_bodies = func_pattern.findall(script.string)
    for body in func_bodies:
        # 从函数体中抓取目标字符串
        results = target_pattern.findall(body)
        for key, value in results:
            print(f"{key}: {value}")

注意:

如果函数体存在嵌套大括号,非贪婪匹配可能失效,可调整正则为r'function answerQuiz\d*\(\)\s*{((?:[^{}]|{[^{}]*})*)}'来适配嵌套结构。

方案二:JavaScript语法解析(精准可靠)

使用esprima库解析JS代码的抽象语法树(AST),能精准识别函数结构,避免正则的局限性。

步骤:

  1. 安装依赖:
pip install esprima
  1. 编写解析代码:
from bs4 import BeautifulSoup
import esprima
import re

soup = BeautifulSoup(html, 'html.parser')
script_tags = soup.find_all('script')
target_pattern = re.compile(r'(Answer|Contents|Quiz)\s*[:=]\s*["\'](.*?)["\']')

for script in script_tags:
    if not script.string:
        continue
    try:
        # 解析JS代码为AST
        ast = esprima.parseScript(script.string)
        # 遍历所有函数声明
        for node in ast.body:
            if (node.type == 'FunctionDeclaration' 
                and node.id.name.startswith('answerQuiz')):
                # 将函数体转为字符串
                func_body = esprima.generate(node.body)
                # 提取目标内容
                results = target_pattern.findall(func_body)
                for key, value in results:
                    print(f"{key}: {value}")
    except Exception:
        # 解析失败时回退到正则方案
        pass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:17:02