import json
import requests
import hashlib


def get_wikidata_image(wikidata_id):
    """Return the image for the Wikidata item with *wikidata_id*. """
    query_string = ("https://www.wikidata.org/wiki/Special:EntityData/%s.json"
                    % wikidata_id)
    item = json.loads(requests.get(query_string).text)

    wdata = item["entities"][wikidata_id]["claims"]

    try:
        image = wdata["P18"][0]["mainsnak"]["datavalue"]["value"].replace(" ", "_")
    except KeyError:
        print("No image on Wikidata.")
    else:
        md = hashlib.md5(image.encode('utf-8')).hexdigest()
        image_url = ("https://upload.wikimedia.org/wikipedia/commons/thumb/%s/%s/%s/64px-%s"
                     % (md[0], md[:2], image, image))
        return image_url