gpt4 book ai didi

python - 如何使用 Python 提取在 HTML 页面 javascript block 中定义的 JSON 对象?

转载 作者:太空狗 更新时间:2023-10-29 16:54:51 27 4
gpt4 key购买 nike

我正在下载以下列方式定义了数据的 HTML 页面:

... <script type= "text/javascript">    window.blog.data = {"activity":{"type":"read"}}; </script> ...

我想提取在“window.blog.data”中定义的 JSON 对象。有没有比手动解析更简单的方法? (我正在研究 Beautiful Soap,但似乎找不到无需解析即可返回确切对象的方法)

谢谢

编辑:使用 python headless 浏览器(例如 Ghost.py)执行此操作是否可能且更正确?

最佳答案

BeautifulSoup 是一个 html 解析器;您还需要一个 javascript 解析器。顺便说一句,一些 javascript 对象文字不是有效的 json(尽管在您的示例中文字也是一个有效的 json 对象)。

在简单的情况下,您可以:

  1. 摘录<script>使用 html 解析器的文本
  2. 假设window.blog...是单行或者没有 ';'在对象内部并使用简单的字符串操作或正则表达式提取 javascript 对象文字
  3. 假设该字符串是一个有效的 json 并使用 json 模块解析它

例子:

#!/usr/bin/env python
html = """<!doctype html>
<title>extract javascript object as json</title>
<script>
// ..
window.blog.data = {"activity":{"type":"read"}};
// ..
</script>
<p>some other html here
"""
import json
import re
from bs4 import BeautifulSoup # $ pip install beautifulsoup4
soup = BeautifulSoup(html)
script = soup.find('script', text=re.compile('window\.blog\.data'))
json_text = re.search(r'^\s*window\.blog\.data\s*=\s*({.*?})\s*;\s*$',
script.string, flags=re.DOTALL | re.MULTILINE).group(1)
data = json.loads(json_text)
assert data['activity']['type'] == 'read'

如果假设不正确,则代码失败。

为了放宽第二个假设,可以使用 javascript 解析器代替正则表达式,例如 slimit ( suggested by @approximatenumber ):

from slimit import ast  # $ pip install slimit
from slimit.parser import Parser as JavascriptParser
from slimit.visitors import nodevisitor

soup = BeautifulSoup(html, 'html.parser')
tree = JavascriptParser().parse(soup.script.string)
obj = next(node.right for node in nodevisitor.visit(tree)
if (isinstance(node, ast.Assign) and
node.left.to_ecma() == 'window.blog.data'))
# HACK: easy way to parse the javascript object literal
data = json.loads(obj.to_ecma()) # NOTE: json format may be slightly different
assert data['activity']['type'] == 'read'

无需将对象文字 ( obj ) 视为 json 对象。要获得必要的信息,obj可以像其他 ast 节点一样递归访问。它将允许支持任意 javascript 代码(可以由 slimit 解析)。

关于python - 如何使用 Python 提取在 HTML 页面 javascript block 中定义的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13323976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com