「Mediawikiのapi取得メモ」の版間の差分
ナビゲーションに移動
検索に移動
Sufee Admin (トーク | 投稿記録) ページの作成:「aaa」 |
Sufee Admin (トーク | 投稿記録) 編集の要約なし |
||
(同じ利用者による、間の2版が非表示) | |||
1行目: | 1行目: | ||
<syntaxhighlight lang="python3"> | |||
from urllib.request import Request, urlopen | |||
from urllib.parse import urlencode | |||
from urllib.error import URLError, HTTPError | |||
import json | |||
def set_params(page_title): | |||
params = { | |||
'action': 'query', | |||
'prop': 'revisions', | |||
'rvprop': 'content', | |||
'titles': page_title, | |||
'formatversion': 2, | |||
'format': 'json', | |||
} | |||
return params | |||
def main(): | |||
request_url = 'https://wiki.sufee.net/api.php?' + urlencode(set_params(input("タイトル->"))) | |||
req = Request(request_url) | |||
try: | |||
with urlopen(req) as res: | |||
res_json = res.read() | |||
except HTTPError as e: | |||
print('HTTPError: {}'.format(e.reason)) | |||
except URLError as e: | |||
print('URLError: {}'.format(e.reason)) | |||
else: | |||
wiki = json.loads(res_json.decode('utf-8')) | |||
print(wiki['query']['pages'][0]['revisions'][0]['content']) | |||
if __name__ == '__main__': | |||
main() | |||
</syntaxhighlight> |
2022年2月7日 (月) 02:05時点における最新版
from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.error import URLError, HTTPError
import json
def set_params(page_title):
params = {
'action': 'query',
'prop': 'revisions',
'rvprop': 'content',
'titles': page_title,
'formatversion': 2,
'format': 'json',
}
return params
def main():
request_url = 'https://wiki.sufee.net/api.php?' + urlencode(set_params(input("タイトル->")))
req = Request(request_url)
try:
with urlopen(req) as res:
res_json = res.read()
except HTTPError as e:
print('HTTPError: {}'.format(e.reason))
except URLError as e:
print('URLError: {}'.format(e.reason))
else:
wiki = json.loads(res_json.decode('utf-8'))
print(wiki['query']['pages'][0]['revisions'][0]['content'])
if __name__ == '__main__':
main()