beautifulsoup extract json from script elements

Solutions on MaxInterview for beautifulsoup extract json from script elements by the best coders in the world

showing results for - "beautifulsoup extract json from script elements"
Bryn
03 Feb 2017
1import json
2from bs4 import BeautifulSoup
3
4html = '''
5<script type="application/json" data-initial-state="review-filter">
6{"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}
7</script>
8'''
9
10soup = BeautifulSoup(html, 'html.parser')
11res = soup.find('script')
12json_object = json.loads(res.contents[0])
13
14for language in json_object['languages']:
15    print('{}: {}'.format(language['displayName'], language['reviewCount']))
similar questions
scrapy json output