Tuesday, January 17, 2017

Logging in with Python Requests

Hi hi. I just figured out how to use the session() object to log into websites using Python Requests. Should work anywhere. Here's the code!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import requests
import re
proxies = { 'http': '', 'https': '',}

#creates a session object to maintain cookies and shtuff
sesh = requests.session()

#gets the login page, you need to do this to extract a token from it
x = sesh.get('https://wikipage.whatever/wiki/index.php/Special:UserLogin', proxies=proxies)

#probably better ways to do this, but an RE will work...
reMatch = re.search('wpLoginToken\"\svalue=\"(.*?)\"', x.content)
token = reMatch.group(1)

#create the POST data.  In order to see what fields you'll need, inspect the request through your browser's debug window (f12 before sending request)
payload={'wpName':'<userHere>', 'wpPassword':'<passHere>', 'wpDomain':'domain', 'wpLoginAttempt':'Log+in', 'wpLoginToken':token}

#logs in.   the "&action=submitlogin&type=login" was also gathered during the previous step.
y = sesh.post('https://wikipage.whatever/wiki/index.php?title=Special:UserLogin&action=submitlogin&type=login', data=payload, proxies=proxies)

#request whatever article you want
z = sesh.get('https://wikipage.whatever/wiki/index.php/articleYouWant', proxies=proxies)

No comments:

Post a Comment