在维基百科上编辑页面,badtoken

时间:2013-12-20 09:00:37

标签: python mediawiki wikipedia-api

我想登录然后编辑页面。我可以使用edittoken,但当我将它传递给action = edit时,它会说badtoken。我错过了什么吗?

__apiJson__ = "https://zh.wikipedia.org/w/api.php?format=json&"
def login():
    username = "???" #use your own
    password = "???" #use your own

    username = urllib.parse.quote(username)
    password = urllib.parse.quote(password)

    r = requests.post(__apiJson__ + "action=login&lgname={username}&lgpassword={password}".
                      format(username=username,password=password))

    content = r.json()
    content = content['login']
    if(content['result'] == 'NeedToken'):
        cookies = r.cookies
        token = content['token']
        r = requests.post(__apiJson__ + "action=login&lgname={username}&lgpassword={password}&lgtoken={token}".
                      format(username=username,password=password,token=token),cookies=cookies)
        content = r.json()
        content = content['login']
        assert content['result']=="Success"
    return r.cookies

def getEditToken(archivePage):
    r = requests.post(__apiJson__ + "action=query&prop=info&intoken=edit&titles={title}".format(title=archivePage),cookies=cookies)
    content = r.json()
    content = content['query']['pages']
    content = content[list(content.keys())[0]]
    editToken = content['edittoken']

    if(editToken == '+\\'):
        raise Exception()
    return editToken

cookies = login()

editToken = getEditToken("User:???/test") #use your own

editToken=urllib.parse.quote(editToken)

r = requests.post("https://zh.wikipedia.org/w/api.php?action=edit&format=json&title=User:Gqqnb/沙盒&text=helloworld&summary=test&token={token}".format(token=editToken),
                  cookies=cookies,headers={"Content-Type":"application/x-www-form-urlencoded"})


content = r.json()

1 个答案:

答案 0 :(得分:1)

我回答我自己的问题。只需使用requests.session(),而不是无会话requests.getpost