javascript - 如何有效地将 JavaScript Json 解析为 Python dict 类型
问题描述
我正在寻找读取加载到此页面的脚本标记之一中的 javascript json 数据的方法。我尝试re
了在谷歌和 stackoveflow 上发布的各种模式,但一无所获。
Json格式化程序显示无效 (RFC 8259)。
这是一个代码
import requests,json
from scrapy.selector import Selector
headers = {'Content-Type': 'application/json', 'Accept-Language': 'en-US,en;q=0.5', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'}
url = 'https://www.zocdoc.com/doctor/andrew-fagelman-md-7363?insuranceCarrier=-1&insurancePlan=-1'
response = requests.get(url,headers = headers)
sel = Selector(text = response.text)
profile_data = sel.css('script:contains(APOLLO_STATE)::text').get('{}').split('__REDUX_STATE__ = JSON.parse(')[-1].split(');\n window.ZD = {')[0]
profile_json = json.loads(profile_data)
print(type(profile_json))
问题似乎是无效的 json 格式。的类型profile_json
是字符串,而上面代码中的一些修改显示在错误堆栈下方
>>> profile_data = sel.css('script:contains(APOLLO_STATE)::text').get('{}').split('__REDUX_STATE__ = JSON.parse("')[-1].split('");\n window.ZD = {')[0].replace("\\","")
>>> profile_json = json.loads(profile_data)
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 41316 (char 41315)
此处突出显示输出错误:
原始 HTML 包含以下内容(经过大量修剪):
<script>
...
window.__REDUX_STATE__ = JSON.parse("{\"routing\": ...
\"awards\":[\"Journal of Urology - \\\"Efficacy, Safety, and Use of Viagra in Clinical Practice.\\\"\",\"Critical Care Resident of the Year - 2003\"],
...
scrapy提取的相同字符串是这样的:
"awards":[
"Journal of Urology - ""Efficacy",
"Safety",
"and Use of Viagra in Clinical Practice.""",
"Critical Care Resident of the Year - 2003"
],
似乎反斜杠已从中删除,从而使 JSON 无效。
解决方案
我不知道这是否是处理问题的有效方法,但下面的代码解决了我的问题。
>>> import js2xml
>>> profile_data = sel.css('script:contains(APOLLO_STATE)::text').get('{}')
>>> parsed = js2xml.parse(profile_data)
>>> js = json.loads(parsed.xpath("//string[contains(text(),'routing')]/text()")[0])
推荐阅读
- sql - 在 SQL 中组合 3 个表并查找水果的计数
- node.js - 节点/npm 说“缺少脚本
" 即使它存在于当前目录中 - android - RecyclerView 上的对象列表
- go - 日志中的 Uber Zap 记录器函数名称
- entity-framework-core - 在 EF Core 中正确管理鉴别器
- arrays - 更改数组状态不会让子组件重新渲染
- reactjs - 将 highcharts 从 8.0.4 升级到 9.0.1 会引发错误 TypeError: e.remove is not a function
- google-apps-script - 当满足 2 个条件时,从 sh1 复制并粘贴到 sh2(GOOGLE SCRIPT)
- autodesk-forge - 对项目用户更新端点的补丁请求失败
- javascript - 使用 .then 的返回类型与没有它的返回类型有什么不同吗?