如何通过 API 以文本形式获取维基百科内容? [英] How to get Wikipedia content as text by API?

查看:93
本文介绍了如何通过 API 以文本形式获取维基百科内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以文本形式获取维基百科页面.

I want to get Wikipedia pages as text.

我从这里查看了维基百科 API https://en.wikipedia.org/w/api.php 表示为了将页面作为文本我需要将其附加到页面地址:

I looked at the Wikipedia API from here https://en.wikipedia.org/w/api.php which says that in order to get pages as text I need to append this to a page address:

api.php?action=query&meta=siteinfo&siprop=namespaces&format=txt

但是,当我尝试将此后缀附加到普通页面的地址时,找不到该页面:

However, when I try appending this suffix to a normal page's address, the page is not found:

https://en.wikipedia.org/wiki/George_Washington/api.php?action=query&meta=siteinfo&siprop=namespaces&format=txt

按照通过API从mediawiki页面获取文本内容,我尝试将/api.php?action=parse&page=test 添加到查询字符串的末尾.因此,我得到了这个:

Following the instructions from Get Text Content from mediawiki page via API, I tried adding /api.php?action=parse&page=test to the end of the query string. Therefore, I obtained this:

https://en.wikipedia.org/wiki/George_Washington/api.php?action=parse&page=test

然而,这也不起作用.

推荐答案

注意:所有这些示例都启用了 CORS.

NB: All this examples are CORS enabled.

从精确的标题中以 json 格式获取文本(如 维基百科页面网址):

https://en.wikipedia.org/w/api.php?action=query&origin=*&prop=extracts&explaintext&titles=Sokolsky_Opening&format=json

按关键字搜索相关页面,获取 ID,获取精确的标题/网址,获取一些快速文本提取;

Search relevant pages by keywords, get IDs, get precise titles/url, get some quick text extract;

https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exlimit=max&format=json&exsentences=1&origin=*&exintro=&explaintext=&generator=search&gsrlimit=23&gsrsearch=chess

通过精确标题获取维基页面 ID:

https://en.wikipedia.org/w/api.php?action=query&origin=*&prop=pageprops&format=json&titles=Sokolsky_Opening

通过 wiki 页面 ID 获取完整的 html:

https://en.wikipedia.org/w/api.php?action=parse&origin=*&format=json&pageid=100017

去掉 html,没有维基数据的轻量级版本.

Get stripped html, lighter version without the wikidata.

https://en.wikipedia.org/w/api.php?action=query&origin=*&prop=extracts&format=json&titles=Sokolsky_Opening

交叉原点:

顺便说一句,使用 CORS 请求,通过知道或搜索 ID 和/或页面标题,我们可以使用 fetch 在 ssl 上下文中的任何位置嵌入一些 wiki 文本.

Btw, using CORS requests, by knowing or searching the ID and/or the page title, we can use fetch to embed some wiki text anywhere, in a ssl context.

如果 ID 未知,我们必须通过 json.

In the event of an unknown ID, we have to loop trough the json.

fetch("https://en.wikipedia.org/w/api.php?action=query&origin=*&prop=extracts&explaintext&format=json&titles=Sokolsky_Opening").then(v => v.json()).then((function(v){
    main.innerHTML = v["query"]["pages"]["100017"]["extract"]
    })
  )

<pre id="main" style="white-space: pre-wrap"></pre>

祝你好运.

这篇关于如何通过 API 以文本形式获取维基百科内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆