ウィキペディアの記事の最初の段落を取得したいと思います。
そうするためのAPIクエリは何ですか?
MediaWikiドキュメントのこのセクションを参照してください。
これらは重要なパラメータです。
prop=revisions&rvprop=content&rvsection=0
rvsection = 0は、リードセクションのみを返すように指定します。
この例を参照してください。
HTMLを取得するには、同様にaction =parsehttp ://en.wikipedia.org/w/api.php ? action=parse §ion=0&prop=text&page=pizzaを使用できます。
テンプレートやインフォボックスを削除する必要があることに注意してください。
コンテンツの概要を取得するためだけのウィキペディアAPIはありますか?を参照してください。他の提案された解決策のために。これが私が提案したものです:
実際には、この目的のために特別に設計されたクエリで使用できる抽出と呼ばれる非常に優れた小道具があります。抽出を使用すると、記事の抽出(切り捨てられた記事のテキスト)を取得できます。ゼロ番目のセクションのテキストを取得するために使用できるexintroと呼ばれるパラメーターがあります(画像やインフォボックスなどの追加のアセットはありません)。また、特定の文字数(exchars)や特定の文数( exsentences)など、より細かい粒度で抽出を取得することもできます。
サンプルクエリ http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro3%titles=Stack%20Overflow とAPIサンドボックス http://en.wikipedia.org/wiki/を次に示します。 Special:ApiSandbox#action = query&prop = extract&format = json&exintro =&titles = Stack%20Overflowを使用して、このクエリをさらに試してください。
特に最初の段落が必要な場合でも、最初のタグを取得する必要があることに注意してください。ただし、このAPI呼び出しでは、解析する画像などの追加のアセットはありません。この概要の概要に満足している場合は、HTMLタグを削除するPHPのstrip_tagなどの関数を実行してテキストを取得できます。
私はそれをこのようにします:
https://en.wikipedia.org/w/api.php?action=opensearch&search=bee&limit=1&format=json
取得する応答は、データを含む配列であり、解析が簡単です。
[
"bee",
[
"Bee"
],
[
"Bees are flying insects closely related to wasps and ants, known for their role in pollination and, in the case of the best-known bee species, the European honey bee, for producing honey and beeswax."
],
[
"https://en.wikipedia.org/wiki/Bee"
]
]
最初の段落だけを取得するlimit=1
ことが必要です。
記事の最初の段落を取得するには:
https://en.wikipedia.org/w/api.php?action=query&titles=Belgrade&prop=extracts&format=json&exintro=1
私は自分のニーズに合わせて短いウィキペディアAPIドキュメントを作成しました。記事や画像などを入手する方法についての実例があります。
多数の記事に対してこれを行う必要がある場合は、Webサイトに直接クエリを実行する代わりに、Wikipediaデータベースダンプをダウンロードして、JWPLなどのAPIを介してアクセスすることを検討してください。
ウィキペディアの記事の紹介は、https://en.wikipedia.org/w/api.php?format = json&action = query&prop = extract&exintro =&explaintext =& titles=javaなどのページにクエリを実行することで取得できます。JSONファイルを解析するだけで、リンクや参照の削除を含めてクリーンアップされたプレーンテキストが作成されます。
<script>
function dowiki(place) {
var URL = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=';
URL += "&titles=" + place;
URL += "&rvprop=content";
URL += "&callback=?";
$.getJSON(URL, function (data) {
var obj = data.query.pages;
var ob = Object.keys(obj)[0];
console.log(obj[ob]["extract"]);
try{
document.getElementById('Label11').textContent = obj[ob]["extract"];
}
catch (err) {
document.getElementById('Label11').textContent = err.message;
}
});
}
</script>
ウィキペディアデータベースを直接ダウンロードし、スタンドアロンアプリケーションであるウィキパーサーを使用してすべてのページをXMLに解析できます。最初の段落は、結果のXMLの個別のノードです。
または、プレーンテキスト出力から最初の段落を抽出することもできます。
jQueryを使用してそれを行うことができます。まず、適切なパラメータを使用してURLを作成します。パラメータの意味を理解するには、このリンクを確認してください。次に、$.ajax()
メソッドを使用して記事を取得します。ウィキペディアではクロスオリジンリクエストは許可されていないことに注意してください。そのためdataType : jsonp
、リクエストで使用しています。
var wikiURL = "https://en.wikipedia.org/w/api.php";
wikiURL += '?' + $.param({
'action' : 'opensearch',
'search' : 'your_search_term',
'prop' : 'revisions',
'rvprop' : 'content',
'format' : 'json',
'limit' : 10
});
$.ajax({
url: wikiURL,
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
extract_html
これには、サマリーRESTエンドポイントのフィールドを使用できます:例: https ://en.wikipedia.org/api/rest_v1/page/summary/Cat 。
注:これは、主に括弧内の発音のほとんどを削除することで、コンテンツを少し単純化することを目的としています。
仮定しkeyword = "Batman" //Term you want to search
て、使用します:
https://en.wikipedia.org/w/api.php?action=parse&page={{keyword}}&format=json&prop=text§ion=0
ウィキペディアからJSON形式で要約/最初の段落を取得します。
フランス語と英語のウィクショナリーとウィキペディアをダンプするプログラムは次のとおりです。
import sys
import asyncio
import urllib.parse
from uuid import uuid4
import httpx
import found
from found import nstore
from found import bstore
from loguru import logger as log
try:
import ujson as json
except ImportError:
import json
# XXX: https://github.com/Delgan/loguru
log.debug("That's it, beautiful and simple logging!")
async def get(http, url, params=None):
response = await http.get(url, params=params)
if response.status_code == 200:
return response.content
log.error("http get failed with url and reponse: {} {}", url, response)
return None
def make_timestamper():
import time
start_monotonic = time.monotonic()
start = time.time()
loop = asyncio.get_event_loop()
def timestamp():
# Wanna be faster than datetime.now().timestamp()
# approximation of current epoch time.
out = start + loop.time() - start_monotonic
out = int(out)
return out
return timestamp
async def wikimedia_titles(http, wiki="https://en.wikipedia.org/"):
log.debug('Started generating asynchronously wiki titles at {}', wiki)
# XXX: https://www.mediawiki.org/wiki/API:Allpages#Python
url = "{}/w/api.php".format(wiki)
params = {
"action": "query",
"format": "json",
"list": "allpages",
"apfilterredir": "nonredirects",
"apfrom": "",
}
while True:
content = await get(http, url, params=params)
if content is None:
continue
content = json.loads(content)
for page in content["query"]["allpages"]:
yield page["title"]
try:
apcontinue = content['continue']['apcontinue']
except KeyError:
return
else:
params["apfrom"] = apcontinue
async def wikimedia_html(http, wiki="https://en.wikipedia.org/", title="Apple"):
# e.g. https://en.wikipedia.org/api/rest_v1/page/html/Apple
url = "{}/api/rest_v1/page/html/{}".format(wiki, urllib.parse.quote(title))
out = await get(http, url)
return wiki, title, out
async def save(tx, data, blob, doc):
uid = uuid4()
doc['html'] = await bstore.get_or_create(tx, blob, doc['html'])
for key, value in doc.items():
nstore.add(tx, data, uid, key, value)
return uid
WIKIS = (
"https://en.wikipedia.org/",
"https://fr.wikipedia.org/",
"https://en.wiktionary.org/",
"https://fr.wiktionary.org/",
)
async def chunks(iterable, size):
# chunk async generator https://stackoverflow.com/a/22045226
while True:
out = list()
for _ in range(size):
try:
item = await iterable.__anext__()
except StopAsyncIteration:
yield out
return
else:
out.append(item)
yield out
async def main():
# logging
log.remove()
log.add(sys.stderr, enqueue=True)
# singleton
timestamper = make_timestamper()
database = await found.open()
data = nstore.make('data', ('sourcery-data',), 3)
blob = bstore.make('blob', ('sourcery-blob',))
async with httpx.AsyncClient() as http:
for wiki in WIKIS:
log.info('Getting started with wiki at {}', wiki)
# Polite limit @ https://en.wikipedia.org/api/rest_v1/
async for chunk in chunks(wikimedia_titles(http, wiki), 200):
log.info('iterate')
coroutines = (wikimedia_html(http, wiki, title) for title in chunk)
items = await asyncio.gather(*coroutines, return_exceptions=True)
for item in items:
if isinstance(item, Exception):
msg = "Failed to fetch html on `{}` with `{}`"
log.error(msg, wiki, item)
continue
wiki, title, html = item
if html is None:
continue
log.debug(
"Fetch `{}` at `{}` with length {}",
title,
wiki,
len(html)
)
doc = dict(
wiki=wiki,
title=title,
html=html,
timestamp=timestamper(),
)
await found.transactional(database, save, data, blob, doc)
if __name__ == "__main__":
asyncio.run(main())
ウィキメディアデータを取得する別のアプローチは、kiwixzimダンプに依存することです。