如何使用Python在脚本中获取JSON数据

2024-04-24 21:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获取在检查特定URL的页面源代码时看到的JSON数据。此URL有多个标记,但是这些标记中只有一个具有JSON格式的数据。你知道吗

以下是我当前的实现:

import urllib2 
from bs4 import BeautifulSoup
import re
import json

url = "https://www.exampleURL.com"

page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
scripts = soup.find_all('script')

for script in scripts:
    try:
        data = json.loads(script)
        print("Success")
    except Exception:
        print("Not Successful")

此实现无法打印成功。我想要的JSON数据的格式如下,但是只有一个脚本标记包含JSON数据,其他所有的都与我无关。你知道吗

<script>
    __DATA__ = {........};
</script>

Tags: 数据标记importjsonurl格式pagescripts
1条回答
网友
1楼 · 发布于 2024-04-24 21:18:22

在尝试将<script>的内容解析为json之前,需要进行一些数据处理。特别是,您需要删除JavaScript字典前面的__DATA__ =部分。你知道吗

要记住的几件事:

  • Javascript字典不一定是JSON blob。特别是

示例

{hello: 2}   # Correct JavaScript, incorrect JSON - missing quotes around key
{'hello': 2} # Correct JavaScript, incorrect JSON - Quotes must be double quotes

{"hello": 2} # Correct JSON and JavaScript

一些可能有助于调试的事情

for script in scripts:
    try:
        print(script) # See what you try to load
        data = json.loads(script)
        print("Success")
    except Exception as e:
        print("Not Successful because {}".format(e)) # Print additional information

相关问题 更多 >