#!/usr/bin/python3

import requests

S = requests.Session()

URL = "https://en.wikipedia.org/w/api.php"
TEST_WIKI_URL = "https://test.wikipedia.org/w/api.php"

TITLE = "Wikimania"

# Step 1: GET Request to parse section 17th of Wikimania page
PARAMS_1 = {
    "action":"parse",
    "prop": "wikitext",
    "page": TITLE,
    "section": 17,
    "format":"json"
}

R = S.get(url=URL, params=PARAMS_1)
DATA = R.json()

PARSED_WIKITEXT = DATA['parse']['wikitext']['*']

# Step 2: Retrieve a login token
PARAMS_2 = {
    "action": "query",
    "meta": "tokens",
    "type": "login",
    "format": "json"
}

R = S.get(url=TEST_WIKI_URL, params=PARAMS_2)
DATA = R.json()

LOGIN_TOKEN = DATA["query"]["tokens"]["logintoken"]

# Step 3: Send a post request to log in. For this login 
# method, Obtain credentials by first visiting
# https://test.wikipedia.org/wiki/Special:BotPasswords/
# See https://www.mediawiki.org/wiki/API:Login for more
# information on log in methods.
PARAMS_3 = {
    "action": "login",
    "lgname": "...",
    "lgpassword": "...",
    "format": "json",
    "lgtoken": LOGIN_TOKEN
}

R = S.post(TEST_WIKI_URL, data=PARAMS_3)

# Step 4: While logged in, retrieve a CSRF token
PARAMS_4 = {
    "action": "query",
    "meta": "tokens",
    "format": "json"
}

R = S.get(url=TEST_WIKI_URL, params=PARAMS_4)
DATA = R.json()

CSRF_TOKEN = DATA["query"]["tokens"]["csrftoken"]

# Step 5: Send a post request to edit a page and append parsed wikitext obtained in Step 1
PARAMS_5 = {
    "action": "edit",
    "title": "User:SSethi_(WMF)/Sandbox",
    "format": "json",
    "appendtext": PARSED_WIKITEXT,
    "token": CSRF_TOKEN,
}

R = S.post(TEST_WIKI_URL, data=PARAMS_5)
DATA = R.json()

print(DATA)
===2019===
[[:wikimania:Wikimania|Wikimania 2019]], the fifteenth Wikimedia conference, will be held in [[Stockholm]], [[Sweden]], from 14 to 18 August 2019.<ref name=Stockholm>{{cite web|url=https://wikimediasverige.wordpress.com/2018/08/22/wikimania-kommer-till-sverige-2019/ |title=Wikimania kommer till Sverige 2019 |date=22 August 2018 |author=Sara Mörtsell |language=Swedish |access-date=4 October 2018 }}</ref>
{'edit': {'result': 'Success', 'pageid': 105632, 'title': 'User:SSethi (WMF)/Sandbox', 'contentmodel': 'wikitext', 'oldrevid': 399915, 'newrevid': 399916, 'newtimestamp': '2019-08-07T02:06:27Z'}}