import pywikibot
from pywikibot import pagegenerators as pg

def wd_sparql_query(spq):
   generator=pg.WikidataSPARQLPageGenerator(spq,site=pywikibot.Site('wikidata','wikidata'))
   for wd in generator:
     try:
       wd.get(get_redirect=True)
       yield wd
     except:
       pass

site = pywikibot.Site('wikidata','wikidata')           #Geef aan naar welke site je wilt schrijven
repo = site.data_repository()                     #voor ophalen wikidata-items adhv Qxxxx
query='SELECT ?item ?population ?pointInTime WHERE {?item p:P1082 [ ps:P1082 ?population; pq:P585 ?pointInTime; prov:wasDerivedFrom [ pr:P248 wd:Q21540096; pr:P854 <https://data.worldbank.org/indicator/SP.POP.TOTL>; pr:P813 \'2019-04-08\'^^xsd:dateTime ] ] .}'
counter=0

def do_rank(wd):
    highest_year=0
    global counter
    if ('P1082' in wd.claims):
        counter+=1
        for c in wd.claims['P1082']:
          if c.has_qualifier:
            for q in c.qualifiers:
              print(q)  
        

#for wd in wd_sparql_query(query):
#  do_rank(wd)
wd=pywikibot.ItemPage(repo,'Q219060')
wd.get(get_redirect=True)
do_rank(wd)
P585
P585