问题
I'm trying to associate to each species name listed in a csv file the wikipedia summary and main image. I write this code:
import csv
import wikipedia
wikipedia.set_lang('it')
with open('D:\\GIS\\Dati\\Vinca\\specie_vinca.csv', 'rt', encoding="utf8") as f:
reader = csv.reader(f)
for row in reader:
wikipage = wikipedia.page(row)
print (wikipage.title)
print (wikipage.summary)
print ("Page URL: %s" % wikipage.url)
print ("Nr. of images on page: %d" % len(wikipage.images))
print (" - Main Image: %s" % wikipage.images[0])
print ("")
but each time it doesn't encounter a species name the script stops wiht this message "wikipedia.exceptions.PageError". How can I skip these records leaving the script finish?
回答1:
The function wikipedia.page
will raise a wikipedia.exceptions.PageError
if the page doesn't exist. That's the error you want to catch.
I will give you an example://maybe its useful to you
import wikipedia
links = ["CPython","no page"]
test=[]
for link in links:
try:
#try to load the wikipedia page
page=wikipedia.page(link, auto_suggest=False)
test.append(page)
except wikipedia.exceptions.PageError:
#if a "PageError" was raised, ignore it and continue to next link
continue
IMPORTANT NOTE:You can use
Try
:Except
to skip those errors and let the script finish
来源:https://stackoverflow.com/questions/42110203/wikipedia-module-python-jumping-wikipedia-exceptions-pageerror