Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Example of Python client calling Knowledge Graph Search API.###############################
- import json
- import urllib
- import urllib.request
- api_key = '**********************************************'
- service_url = 'https://kgsearch.googleapis.com/v1/entities:search'
- '''
- The Knowledge Graph API Search API allows developers a free quota of up to 100,000 (one hundred thousand) read calls per day per project. We believe this meets the needs of the vast majority of developers.
- '''
- # Name to query (str)
- query = 'jeremy'
- params = {
- 'query': query,
- 'limit': 20,
- 'indent': True,
- 'key': api_key,
- }
- url = "{}{}{}". format(service_url, '?', urllib.parse.urlencode(params))
- data = json.loads(urllib.request.urlopen(url).read())
- result = [
- {'name':item['result'].get('name',''),
- 'description':item['result']['detailedDescription'].get('articleBody', ''),
- 'image':item['result'].get('image', '').get('contentUrl') if 'contentUrl' in item['result'].get('image', '') else item['result'].get('image', '') }
- for item in data['itemListElement']
- if "Person" in item['result']['@type']
- ]
- print(json.dumps(result[:3], indent=2, sort_keys=True))
- ## Example Output ################################################################
- '''
- [
- {
- "description": "Jeremy Bernard Corbyn is a British politician serving as Leader of the Labour Party and Leader of the Opposition since 2015. Corbyn was first elected Member of Parliament for Islington North in 1983. ",
- "image": "http://t0.gstatic.com/images?q=tbn:ANd9GcQyAH71ISMcdvSUkM_ndk8s38nd4tspRNJZ3Vi9KUx72Pmbqo5g",
- "name": "Jeremy Corbyn"
- },
- {
- "description": "Jeremy Charles Robert Clarkson is an English broadcaster, journalist and writer who specialises in motoring. He is best known for co-presenting the BBC TV show Top Gear with Richard Hammond and James May from October 2002 to March 2015. ",
- "image": "http://t3.gstatic.com/images?q=tbn:ANd9GcTkIpzT0beHgqJWVkTTjg71OFDMV-w_px6PIjzGZndZGGkIOpCQ",
- "name": "Jeremy Clarkson"
- },
- {
- "description": "Jeremy Richard Streynsham Hunt is a British Conservative Party politician serving as British Foreign Secretary since 2018 and Member of Parliament for South West Surrey since 2005. ",
- "image": "http://t0.gstatic.com/images?q=tbn:ANd9GcRIP0Amx6SZDtyUsw4Q7idJGj4yJ_NTiVz05b8HOBD3HNWRUymN",
- "name": "Jeremy Hunt"
- }
- ]
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement