python - 无法从奇怪的 json 内容中获取项目

标签 python json python-3.x web-scraping

我正在尝试从 json 内容中获取一些项目。但是,该 json 内容的结构对我来说是陌生的,因此我无法从中获取 property 的值。

到目前为止我已经尝试过:

import json
import requests
from bs4 import BeautifulSoup

link = 'https://www.zillow.com/homedetails/5958-SW-4th-St-Miami-FL-33144/43835884_zpid/'

def fetch_content(link):
    content = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(content.text,"lxml")
    item = soup.select_one("script#hdpApolloPreloadedData").text
    print(json.loads(item)['apiCache'])

if __name__ == '__main__':
    fetch_content(link)

运行上述脚本的结果是:

{"VariantQuery{\"zpid\":43835884}":{"property":{"zpid":43835884,"streetAddress":"5958 SW 4th St",

我无法进一步处理前面那个奇怪的 key 。

预期输出:

{"zpid":43835884,"streetAddress":"5958 SW 4th St", ----

我怎样才能获得该属性(property)的值(value)?

最佳答案

您可以通过其损坏的 json 获取 zpid 和地址:

json.loads(json.loads(item.text)['apiCache'])['VariantQuery{"zpid":43835884}']['property']['zpid']                                                                                  
Out[1889]: 43835884

json.loads(json.loads(item.text)['apiCache'])['VariantQuery{"zpid":43835884}']['property']['streetAddress']                                                                         
Out[1890]: '5958 SW 4th St'

我注意到你总是可以像这样获取 zpid:

link = 'https://www.zillow.com/homedetails/5958-SW-4th-St-Miami-FL-33144/43835884_zpid/'
content = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(content.text,"lxml")
item = soup.select_one("script#hdpApolloPreloadedData").text
print(json.loads(item)['zpid'])

关于python - 无法从奇怪的 json 内容中获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59434057/

相关文章:

javascript - 如何使用 Angular 过滤器过滤json

json - Play json 将缺失字段解析为空数组

c# - 如何在 C# 中解析 JsonObject

python - Python Asyncio队列获取未收到消息

python - 列出每行中 Dataframe 为 NULL/Empty 的列名

python - 按日期和时间查询存储在 MongoDB 中的数据

python - 在 Peewee 中获取查询结果列表

python - 如何按分组索引访问 pandas groupby 数据框?

python-3.x - 使用 Homebrew 软件安装但未使用更新版本的 Python3

python - 制作延伸到其父窗口之外的 Qt 小部件的图表