我正在尝试编写一个脚本,该脚本尝试获取经过验证的帐户的某些Instagram用户名,并检查是否有链接到该用户名的Wikipedia页面。在某些情况下,它什么也找不到,并向我返回此错误:
wikipedia.exceptions.PageError: Page id "dana junctella" does not match any pages. Try another id!
所以我尝试使用以下代码进行处理:
def getWikiData(username):
global text
try:
print(username)
url = 'https://query.wikidata.org/sparql'
query = """
SELECT ?item ?itemLabel WHERE {
?item wdt:P2003 '"""+username+"""'.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
"""
r = requests.get(url, params = {'format':'json', 'query':query})
r = r.json()
wikiurl = r['results']['bindings'][0]['item']['value']
wiki_id = wikiurl.replace("http://www.wikidata.org/entity/", "")
wikipage = requests.get("https://www.wikidata.org/w/api.php?action=wbgetentities&props=sitelinks&format=json&ids="+wiki_id+"&sitefilter=enwiki&languages=en")
data = wikipage.json()
pedia_name = data['entities'][wiki_id]['sitelinks']['enwiki']['title']
text = wikipedia.summary(pedia_name)
text = text.split(".")
text = text[0]
return text
except wikipedia.exceptions.PageError:
return
except Exception as e:
profile = Profile.from_username(L.context, username)
username = profile.full_name
username = ''.join(c for c in username if unicodedata.category(c) != 'Cc')
text = wikipedia.summary(username)
text = text.split(".")
text = text[0]
return text
看看第一个例外。好。问题是,即使我运行此脚本,当发生错误时,代码也会结束,IDE会在我的屏幕上打印错误,而不是进行处理。 如何解决?谢谢您的建议。