import pywikibot
import requests
from pywikibot import pagegenerators as pg
from datetime import datetime, date, time

baseURL='https://www.instagram.com/%s/'
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 where {?item wdt:P2003 ?insta}'
nr_of_subs='P3744'
retrieved='P813'

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


def strip_int(text):
    number=''.join(c for c in text if c in '0123456789')
    if number!='': 
       return(int(number))
    return(0)
    

def readInstaProfile(id):
  f = requests.get(baseURL%id) 
  start=f.text.find('<meta property="og:description"')
  end=f.text[start:].find('/>')
  tagstr=f.text[start:start+end]
  start=tagstr.find('content="')  
  end=tagstr.find('Followers,')
  value=strip_int(tagstr[start+9:end])  
  return(value)

def loop_query(query):
 i=0    
 for wd in wd_sparql_query(query):
  just_one(wd)      
  i+=1
  if i>10: x=10/0
        
def just_one_wd(wd):        
  if (not('P2003' in wd.claims)): return Null
  insta=wd.claims['P2003'][0].getTarget()
  if wd.claims['P2003'][0].has_qualifier(nr_of_subs,414):
    print('has qualifier')
    
  #print(f'{insta}-{readInstaProfile(insta)}')
  return(readInstaProfile(insta))

def just_one_Q(Qitem):
  wd=pywikibot.ItemPage(repo,Qitem)
  wd.get(get_redirect=True)
  return(just_one_wd(wd))

def wd_add_int(wd,claimstr,value,multiClaim=False,summary='add integer'):
    if (claimstr in wd.claims) and (not multiClaim):
      return()  
    newclaim=pywikibot.Claim(repo,claimstr)
    newtarget=pywikibot.WbQuantity(value)
    newclaim.setTarget(newtarget)
    wditem.addClaim(newclaim,summary=summary)

print(just_one_Q('Q13733466'))
    
414
def x(mode=True):
  return(mode)

print(x())
print('OK!')    
True
OK!