维基百科模块 python:跳跃 "wikipedia.exceptions.PageError"
Wikipedia module python: jumping "wikipedia.exceptions.PageError"
我正在尝试将 csv 文件中列出的每个物种名称与维基百科摘要和主要图像相关联。
我写这段代码:
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 ("")
但每次没有遇到物种名称时,脚本都会停止并显示此消息 "wikipedia.exceptions.PageError"。
我怎样才能跳过这些记录让脚本完成?
如果页面不存在,函数 wikipedia.page
将引发 wikipedia.exceptions.PageError
。这就是您要捕获的错误。
我给你举个例子://也许对你有用
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
我正在尝试将 csv 文件中列出的每个物种名称与维基百科摘要和主要图像相关联。 我写这段代码:
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 ("")
但每次没有遇到物种名称时,脚本都会停止并显示此消息 "wikipedia.exceptions.PageError"。 我怎样才能跳过这些记录让脚本完成?
如果页面不存在,函数 wikipedia.page
将引发 wikipedia.exceptions.PageError
。这就是您要捕获的错误。
我给你举个例子://也许对你有用
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