【问题标题】:json not loads data properlyjson 无法正确加载数据
【发布时间】:2019-10-23 18:18:28
【问题描述】:

我正在尝试从网页中截取嵌入的 json,然后将 json 对象传递给 json.loads()。第一个 url 没问题,但是加载第二个 url 时返回错误

ValueError:未终止的字符串开始于:第 1 行第 2078 列(字符 2077)

这里是代码

import requests,json
from bs4 import BeautifulSoup

urls = ['https://www.autotrader.co.uk/dealers/greater-manchester/manchester/williams-landrover-9994',
'https://www.autotrader.co.uk/dealers/warwickshire/stratford-upon-avon/guy-salmon-land-rover-stratford-upon-avon-9965'
]

for url in urls:
    r = requests.get(url)
    soup = BeautifulSoup(r.content,'lxml')
    scripts = soup.find_all('script')[0]
    data = scripts.text.split("window['AT_APOLLO_STATE'] = ")[1].split(';')[0]
    jdata = json.loads(data)
    print(jdata)

【问题讨论】:

  • 在json.loads之前添加print(data),这样你就可以看到抓取的输出了。

标签: python json web-scraping beautifulsoup


【解决方案1】:

已经给出了原因。您还可以正则表达式输出适当的字符串

import requests,json

urls = ['https://www.autotrader.co.uk/dealers/greater-manchester/manchester/williams-landrover-9994',
'https://www.autotrader.co.uk/dealers/warwickshire/stratford-upon-avon/guy-salmon-land-rover-stratford-upon-avon-9965'
]

p = re.compile(r"window\['AT_APOLLO_STATE'\] =(.*?});", re.DOTALL)
for url in urls:
    r = requests.get(url)
    jdata = json.loads(p.findall(r.text)[0])
    print(jdata)

在原帖中遗漏了}。

【讨论】:

    【解决方案2】:

    如果您打印出scripts.text.split("window['AT_APOLLO_STATE'] = ")[1],您将看到在and enthusiastic 之后包含; 的以下内容。所以你从scripts.text.split("window['AT_APOLLO_STATE'] = ")[1].split(';')[0] 得到一个无效的 json 字符串。并且数据以and enthusiastic 结尾,这不是一个有效的json 字符串。

    "strapline":"In our state-of-the-art dealerships across the U.K, Sytner Group represents the world’s most prestigious car manufacturers. All of our staff are knowledgeable and enthusiastic; making every interaction special by going the extra mile.",

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2018-02-07
      • 1970-01-01
      • 2014-04-05
      相关资源
      最近更新 更多