gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:54:00 26 4
gpt4 key购买 nike

我正在尝试从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com