本文介绍如何从 html 页面的 `<script>` 标签中精准提取 <a style="color:#f60; text-decoration:underline;" title= "javascript" href="https://www.php.cn/zt/15724.html" target="_blank">javascript 对象(如 `<a style="color:#f60; text-decoration:underline;" title= "app" href="https://www.php.cn/zt/16186.html" target="_blank">app = { … };`),并安全转换为 <a style="color:#f60; text-decoration:underline;" title= "python" href="https://www.php.cn/zt/15730.html" target="_blank">python 字典,避免字符串暴力替换引发的解析错误。核心方法是定位脚本、剥离 <a style="color:#f60; text-decoration:underline;" title= "js" href="https://www.php.cn/zt/15802.html" target="_blank">js 语法包裹、截取合法 <a style="color:#f60; text-decoration:underline;" title= "json" href="https://www.php.cn/zt/15848.html" target="_blank">json 片段后调用 `json.loads()`。</script>
在现代动态网站中,许多新闻列表、产品数据或配置信息并非通过传统 DOM 元素渲染,而是以 JavaScript 对象字面量(如 App = { … }; 或 window.DATA = {…};)的形式内联在 <script> 标签中。这类数据虽非标准 JSON,但结构上高度兼容——只需准确剥离外围 JS 语法(如变量声明、分号、注释等),即可交由 Python 的 json 模块安全解析。</script>
以下是一个健壮、通用的解析流程,适用于 App = {…}; 类型的嵌入式数据: