8

I want to get main image from wikipedia page, I have all wikipedia entity name from which I create wiki link and getting main image from that page.

I tried with

https://github.com/richardasaurus/wiki-api, https://github.com/goldsmith/Wikipedia

But this does not work on all pages though page contains image.

from wikiapi import WikiApi
wiki = WikiApi()
wiki = WikiApi({ 'locale' : 'es'})
def getWikiImage(entity):
    results = wiki.find(entity)
    print results
    if len(results):
        article = wiki.get_article(results[0])
        print article.image
#getWikiImage("Rudy Sarzo")
getWikiImage("Melody Gersbach")

mediawiki api at http://www.mediawiki.org/wiki/API:Client_code#Python I checked out, but does not seem to help.

2
  • On what page does this not work?
    – user1907906
    Jun 2, 2015 at 12:23
  • @LutzHorn: please check updated descriptio
    – nlper
    Jun 2, 2015 at 12:25

2 Answers 2

11

This returns the url of the main image of the article, not the random one:

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')
4

Here is little example how to get wikipage and main image should be the first one on the page.

import wikipedia

PAGES = ['New York', 'Mercury_(planet)', 'Tucana']

for page in PAGES:
    wikipage = wikipedia.page(page)
    print "Page Title: %s" % wikipage.title
    print "Page URL: %s" % wikipage.url
    print "Nr. of images on page: %d" % len(wikipage.images)
    print " - Main Image: %s" % wikipage.images[0]
    print ""

Checkout out Quickstart guide for Wikipedia API.

3
  • 6
    Seems like wikipage.images[0] doesn't return the main image (upper right) now, but it returns random picture from the article Nov 8, 2018 at 12:08
  • 2
    @DmytroSytro I know this is two years ago but did you find a way to get the main image and not a random
    – GILO
    Apr 7, 2020 at 9:32
  • @GILO Yeah, check my answer Apr 8, 2020 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.