I have tried to solve this issue but there is no way (for me) to resume next after raising the error in Python.
I am querying this site: https://w.wiki/msg I adjust the query by changing the City for each loop, the cities are inside the [listElements]. The code interrupts, when I have a city like "Awaradam". (You could basically hard code it instead of the listElement)
Trying to put a sleep timer inside was not solving the issue (I thought I am attempting to often a request).
The error is the following:
Traceback (most recent call last):
File "C:/Users/xxx/PycharmProjects/pythonProject3/xxx.py", line 30, in <module>
data = r.json()
File "C:\ProgramData\Anaconda3\envs\pythonProject3\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\ProgramData\Anaconda3\envs\pythonProject3\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\ProgramData\Anaconda3\envs\pythonProject3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\ProgramData\Anaconda3\envs\pythonProject3\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Code (I edited it, so it can be reproduced, as of now it makes no sense to have a code like that, after a certain time of loops it just interrupts):
import requests
listPops = [[], []]
url = 'https://query.wikidata.org/sparql'
zaehler = -1
for i in range(100):
zaehler = zaehler + 1
#print(str(listElements[1][i]))
#query = r"SELECT ?population WHERE { SERVICE wikibase:mwapi {bd:serviceParam mwapi:search '" + str(listElements[1][i]) + "' . bd:serviceParam mwapi:language 'en' . bd:serviceParam wikibase:api 'EntitySearch' . bd:serviceParam wikibase:endpoint 'www.wikidata.org' . bd:serviceParam wikibase:limit 1 . ?item wikibase:apiOutputItem mwapi:item .} ?item wdt:P1082 ?population} "
query = """ SELECT ?population WHERE { SERVICE wikibase:mwapi {
bd:serviceParam mwapi:search '""" + "Awaradam" + """'.
bd:serviceParam mwapi:language "en" .
bd:serviceParam wikibase:api "EntitySearch" .
bd:serviceParam wikibase:endpoint "www.wikidata.org" .
bd:serviceParam wikibase:limit 1 .
?item wikibase:apiOutputItem mwapi:item .
}
?item wdt:P1082 ?population
}
"""
r = requests.get(url, params={'format': 'json', 'query': query}, timeout=10)
#time.sleep(5)
data = r.json()
try:
#population = r['results']['bindings'][0]['population']['value']
if data['results']['bindings'][0]['population']['value']:
population = data['results']['bindings'][0]['population']['value']
print(str(zaehler) + ": " + "Population in " + str(listElements[1][i]) + ": " + f"{int(population):,}")
listPops[0].append(str(listElements[1][i]))
listPops[1].append(population)
except:
continue
print('Finished scrape.')