假设我有一个宇航员列表,我想使用Wikipedia API显示他们的传记。
到目前为止,我已经尝试了以下方法:

https://en.wikipedia.org/w/api.php?action=parse&prop=wikitext&page=Nick%20Hague

可以正常工作。但是看看这个例子:
https://en.wikipedia.org/w/api.php?action=parse&prop=wikitext&page=Andrew%20Morgan

如您所见,存在多个“Andrew Morgan”,这就是问题所在。如果他是NASA宇航员,我如何获得“安德鲁·R·摩根”信息。
请注意,“Andrew Morgan”只是一个示例,可能会更改。这些名称将从其他API发送给我。所以我不能每次都手动更改他们的名字。

最佳答案

歧义消除页面都归类为“所有歧义消除页面”,因此您可以检查该类别以查看是否在歧义消除页面上。

因此,您可以检查“All_disambiguation_pages”是否作为类别存在,以确定您是否在消歧页面上。使用查询https://en.wikipedia.org/w/api.php?action=parse&prop=categories&page=Andrew%20Morgan:

for (category of r.parse.categories) {
    if (Object.values(category).includes("All_disambiguation_pages")) {
        // we know it's a disambiguation page
    }
}

另外,您还可以使用查询来检查“歧义消除”属性:

https://en.wikipedia.org/w/api.php?action=query&prop=pageprops&ppprop=disambiguation&redirects&format=xml&titles=Andrew%20Morgan

当然,这些仅告诉您该页面是否是歧义页面。最终,您需要知道要查找的内容。就“安德鲁·摩根”而言,宇航员在“安德鲁·R·摩根”之下。但是有些文章可能使用“John Doe(宇航员)”或其他一些标题。这没有真正的标准化。

对于“astronaut”的示例,您也许可以在歧义消除页面中搜索关键字“astronaut”,然后转到该文章:

fetch('https://en.wikipedia.org/w/api.php?action=opensearch&search=andrew%20morgan&format=json&origin=*')
  .then(function(response) {
    response.json().then(function(data) {
      // data[1] is the array of titles, [2] is the array of descriptions, [3] is the array of links
      let articleUrl = data[3][data[2].findIndex(element => element.includes("astronaut"))];
      if (articleUrl !== -1) { // -1 would be not found
        console.log(articleUrl); //the url
      }
    });
  });

08-25 09:54