gpt4 book ai didi

python - 如何使用漂亮的汤 python 从脚本标签中提取 json?

转载 作者:行者123 更新时间:2023-12-04 00:01:12 28 4
gpt4 key购买 nike

我想提取 reviewCount从脚本标签使用 BeautifulSoup 。尝试了不同的方法,但没有成功。

<script type="application/json" data-initial-state="review-filter">
{"languages":[{"isoCode":"all","displayName":"Toutes les langues","reviewCount":"573"},{"isoCode":"fr","displayName":"français","reviewCount":"567"},{"isoCode":"en","displayName":"English","reviewCount":"6"}],"selectedLanguages":["all"],"selectedStars":null,"selectedLocationId":null}
</script>

最佳答案

这应该有效,我绝对确定有一种更优雅的方法:

import json
from bs4 import BeautifulSoup

html = '''
<script type="application/json" data-initial-state="review-filter">
{"languages":[{"isoCode":"all","displayName":"Toutes les langues","reviewCount":"573"},{"isoCode":"fr","displayName":"français","reviewCount":"567"},{"isoCode":"en","displayName":"English","reviewCount":"6"}],"selectedLanguages":["all"],"selectedStars":null,"selectedLocationId":null}
</script>
'''

soup = BeautifulSoup(html, 'html.parser')
res = soup.find('script')
json_object = json.loads(res.contents[0])

for language in json_object['languages']:
print('{}: {}'.format(language['displayName'], language['reviewCount']))

输出:
Toutes les langues: 573
français: 567
English: 6

关于python - 如何使用漂亮的汤 python 从脚本标签中提取 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61217541/

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