image from wikipedia module in python 1

image from wikipedia module in python

import wikipedia
import requests
import json

WIKI_REQUEST = 'http://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=original&titles='

def get_wiki_image(search_term):
    try:
        result = wikipedia.search(search_term, results = 1)
        wikipedia.set_lang('en')
        wkpage = wikipedia.WikipediaPage(title = result[0])
        title = wkpage.title
        response  = requests.get(WIKI_REQUEST+title)
        json_data = json.loads(response.text)
        img_link = list(json_data['query']['pages'].values())[0]['original']['source']
        return img_link        
    except:
        return 0

wiki_image = get_wiki_image('Paris City')

Here is what the above code is Doing:
1. We are using the wikipedia module to search for the term ‘Paris City’ and get the first result.
2. We are using the WikipediaPage method to get the page object of the first result.
3. We are using the title attribute of the page object to get the title of the page.
4. We are using the requests module to make a GET request to the Wikipedia API.
5. We are using the json module to parse the response.
6. We are using the json_data variable to get the image link from the response.
7. We are returning the image link.

Similar Posts