Wikipedia module python: jumping “wikipedia.exceptions.PageError”

允我心安 提交于 2020-01-07 03:13:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!