如何使用 Python 提取在 HTML 页面 javascript 块中定义的 JSON 对象? [英] How to extract a JSON object that was defined in a HTML page javascript block using Python?

查看:22
本文介绍了如何使用 Python 提取在 HTML 页面 javascript 块中定义的 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am downloading HTML pages that have data defined in them in the following way:

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

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

I would like to extract the JSON object defined in 'window.blog.data'. Is there a simpler way than parsing it manually? (I am looking into Beautiful Soap but can't seem to find a method that will return the exact object without parsing)

谢谢

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

Would it be possible and more correct to do this with a python headless browser (e.g., Ghost.py)?

推荐答案

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

BeautifulSoup is an html parser; you also need a javascript parser here. btw, some javascript object literals are not valid json (though in your example the literal is also a valid json object).

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

In simple cases you could:

  1. 使用 html 解析器提取
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆