Mediawikiのapi取得メモ

提供:sufeeWiki
ナビゲーションに移動 検索に移動
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()