假设我有一个宇航员列表,我想使用维基百科 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 宇航员,我如何获得“Andrew R. Morgan”信息。
请注意,“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
}
}
或者,您也可以使用以下查询检查“消歧义”属性:
当然,这些只告诉你页面是否是消歧页面。最终,您需要知道自己在寻找什么。在“Andrew Morgan”的情况下,宇航员在“Andrew R. Morgan”之下。但有些文章可能会使用“John Doe (Astronaut)”或其他一些标题。这没有真正的标准化。
以“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
}
});
});
关于javascript - 如何使用 Wikipedia API 在页面列表中查找具有相同姓名的人的特定人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58061298/