import pywikibot
import re
from pywikibot import pagegenerators as pg

site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

positionProperty = "P39" # Position held
position = "Q27169" # Member of the European Parliament
referenceProperty = "P854" # reference url
summary = "Fixing reference to europarl.europa.eu website"

# MEPs with 'parliamentary term' as '1st european parliament' and 'elected in' as 'European Parliament Elections 1989'
QUERY = """
SELECT ?item ?itemLabel WHERE { ?item wdt:%s wd:%s. } LIMIT 1
""" % (positionProperty, position)
print(QUERY)
generator = pg.WikidataSPARQLPageGenerator(QUERY, site=site)
for index, entity in enumerate(generator):
    print("assessing item " + str(index +1) + ": " + entity.id)
SELECT ?item ?itemLabel WHERE { ?item wdt:P39 wd:Q27169. } LIMIT 1

<generator object WikidataSPARQLPageGenerator.<locals>.<genexpr> at 0x7fd112614048>
assessing item 1: Q157