Python未读取有效的JSON

2024-04-25 09:55:43 发布

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

我从一个网页抓取一些HTML源代码,以提取以json格式存储的数据

代码如下:

url = 'https://finance.yahoo.com/quote/SPY'
result = requests.get(url)

c = result.content
html = BeautifulSoup(c, 'html.parser')
scripts = html.find_all('script')

sl =[]
for s in scripts:

     sl.append(s)

s = (sl[-3])
s = s.contents
s = str(s)
s = s[119:-16]

json_data = json.loads(s)

运行上述命令会引发此错误:

json.decoder.JSONDecodError: Expecting ',' delimiter: line 1 column 7506 (char7505)

当我获取变量s的内容并将其传递给json格式化程序时,它被认为是正确的json。你知道吗

我使用以下网站检查json: http://jsonprettyprint.com/json-pretty-printer.php

为什么使用时会出现此错误json.loads文件()在Python中?我假设这与字符串编码不正确或存在转义字符有关?你知道吗

我该怎么解决这个问题?你知道吗


Tags: 数据代码comjsonurl网页源代码html
3条回答
import requests
from bs4 import BeautifulSoup
import json

url = 'https://finance.yahoo.com/quote/SPY'
result = requests.get(url)

c = result.content
html = BeautifulSoup(c, 'html.parser')
scripts = html.find_all('script')

sl =[]
for s in scripts:

     sl.append(s)

s = (sl[-3])
s = s.contents

a = s[0][111:-12]

jjjj = json.loads(a)

当你处理这个列表的时候,你只需要使用str()就行了

您的JSON包含某些意外的标记,如true。首先使用json.dumps来解析它。你知道吗

print (json.dumps(s,indent =2))
s = json.dumps(s)
json_data = json.loads(s)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 7484 (char 7483)

使用失败消息,您可以打印字符串的一部分,以查看失败的位置。你知道吗

print(s[7400:7500])
mailboxes.isPrimary=\\"true\\" AND ymreq

正如skaul05所说,它失败是因为字符串中的true标记。你知道吗

相关问题 更多 >