我正在从网页中抓取一些 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
为什么在 Python 中使用 json.loads() 时会出现此错误?我假设它与未正确编码的字符串或存在转义字符有关?
我该如何解决?
最佳答案
您的 JSON 包含某些意外标记,例如 true
。先用json.dumps
解决。
print (json.dumps(s,indent =2))
s = json.dumps(s)
json_data = json.loads(s)
关于Python 没有读取有效的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056192/