Python:在异常时返回空值

Python:在异常时返回空值,python,try-catch,wikipedia-api,pywikibot,Python,Try Catch,Wikipedia Api,Pywikibot,我有一些Python方面的经验,但我从未使用try&except函数来捕捉由于缺乏正式培训而产生的错误 我正在从维基百科摘录一些文章。为此,我有一系列的标题,其中一些没有任何文章或搜索结果在最后。我希望页面检索功能只跳过这几个名称,并继续在其余部分上运行脚本。可复制代码如下 import wikipedia # This one works. links = ["CPython"] test = [wikipedia.page(link, auto_suggest=False) for link

我有一些Python方面的经验,但我从未使用try&except函数来捕捉由于缺乏正式培训而产生的错误

我正在从维基百科摘录一些文章。为此,我有一系列的标题,其中一些没有任何文章或搜索结果在最后。我希望页面检索功能只跳过这几个名称,并继续在其余部分上运行脚本。可复制代码如下

import wikipedia
# This one works.
links = ["CPython"]
test = [wikipedia.page(link, auto_suggest=False) for link in links]
test = [testitem.content for testitem in test]
print(test)

#The sequence breaks down if there is no wikipedia page.
links = ["CPython","no page"]
test = [wikipedia.page(link, auto_suggest=False) for link in links]
test = [testitem.content for testitem in test]
print(test)
运行它的库使用这样的方法。通常情况下,这将是非常糟糕的做法,但由于这只是一次一次性的数据提取,我愿意更改库的本地副本以使其正常工作编辑我现在包括了完整的功能

def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False):
  '''
  Get a WikipediaPage object for the page with title `title` or the pageid
  `pageid` (mutually exclusive).

  Keyword arguments:

  * title - the title of the page to load
  * pageid - the numeric pageid of the page to load
  * auto_suggest - let Wikipedia find a valid page title for the query
  * redirect - allow redirection without raising RedirectError
  * preload - load content, summary, images, references, and links during initialization
  '''
  if title is not None:
    if auto_suggest:
      results, suggestion = search(title, results=1, suggestion=True)
      try:
        title = suggestion or results[0]
      except IndexError:
        # if there is no suggestion or search results, the page doesn't exist
        raise PageError(title)
    return WikipediaPage(title, redirect=redirect, preload=preload)
  elif pageid is not None:
    return WikipediaPage(pageid=pageid, preload=preload)
  else:
    raise ValueError("Either a title or a pageid must be specified")

我应该怎么做才能只检索那些没有给出错误的页面呢。也许有一种方法可以过滤掉列表中出现此错误或某种错误的所有项目。对于不存在的页面,返回“NA”或类似的值是可以的。在没有通知的情况下跳过它们也可以。谢谢

请理解,这将是一种不好的做法,但对于一次性快速脏脚本,您可以:

编辑:等等,对不起。我刚刚注意到这个列表。事实上,我不确定这是否能在不破坏它的情况下起作用:

links = ["CPython", "no page"]
test = []
for link in links:
    try:
        page = wikipedia.page(link, auto_suggest=False)
        test.append(page)
    except wikipedia.exceptions.PageError:
        pass
test = [testitem.content for testitem in test]
print(test)

pass
告诉python从本质上信任您并忽略错误,这样它就可以继续运行。

如果页面不存在,函数
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

您必须用try块将函数
wikipedia.page
包围起来,因此我担心您无法使用列表理解功能。

谢谢,我会记住这是一种不好的做法。不过,当前的代码并没有为我修复它。我仍然得到
wikipedia.exceptions.PageError:Page id“no Page”与任何页面都不匹配。试试别的身份证可能是版本问题,我使用的是Python 3.5.0。我建议不要在
try
块中放置无论如何都不会失败的东西。像我一样。此外,索引器被捕获,然后抛出一个PageError,因此您无法捕获索引器“更高”的位置。try块不是一种坏做法,只要您只捕获特定错误<代码>例外:
将跳过任何错误,这是一种不好的做法。无论如何,这里的问题不是
索引器的问题。现在还为时过早,@puslet88这应该是您所需要的。谢谢您的帮助,@tmoreau和@cssko,非常感谢。我想我可能遗漏了一些要点。此代码运行时没有错误,但因为
auto_suggest=True
建议使用“主页”而不是“无页面”。如果我关闭自动建议,它仍然会坏。它是如何坏的?我刚刚删除了
auto_suggest
,因为我懒得键入它,我不知道该函数实际上是做什么的。是的,对不起,我包括了整个函数。不幸的是,我不得不承认,我只有90%的把握认为这是需要处理的函数。当
auto\u suggest=True
时,无错误捕获的版本也可以工作。很抱歉混淆了。是的,非常感谢,这修复了两个答案!现在catch和except函数对我来说也更清晰了。再次感谢!