如何从维基百科API获得干净的json



我想从维基百科页面https://en.wikipedia.org/wiki/February_2获得JSON的结果。

我尝试使用他们的API: https://en.wikipedia.org/w/api.php?action=parse&page=February_19∝text&formatversion=2&format=json

虽然它是给它作为Json格式。内容是HTML。我只需要内容。

我需要一种方法来获得干净的结果。

如果需要不带标记的纯文本,则必须首先解析JSON对象,然后从HTML代码中提取文本:

function htmlToText(html) {
let tempDiv = document.createElement("div");
tempDiv.innerHTML = html;
return tempDiv.textContent || tempDiv.innerText || "";
}
const url = 'https://en.wikipedia.org/w/api.php?action=parse&page=February_19&prop=text&format=json&formatversion=2&origin=*';
$.getJSON(url, function(data) {
const html = data['parse']['text'];
const plainText = htmlToText(html);
const array = [...plainText.matchAll(/^d{4} *–.*/gm)].map(x=>x[0]);
console.log(array);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

我根据下面的注释编辑了上面的代码。现在,该函数提取所有列表项,并将它们放入一个数组中。

我猜你说的clean指的是源维基文本。在这种情况下,您可以使用revisions模块:

https://en.wikipedia.org/w/api.php?action=query&标题= February_2&支持= revisions& rvprop = content& formatversion = 2, = json格式的

更多信息请参见API:获取页面内容和API:修订版。

最新更新