Created
February 12, 2012 02:46
-
-
Save yosemitebandit/1805918 to your computer and use it in GitHub Desktop.
using the request lib's sessions to login; bonus: beautiful soup finds the csrf token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
''' | |
testing a login to meduele using sessions | |
meduele checks csrf tokens with every request, even during login | |
''' | |
import requests | |
from BeautifulSoup import BeautifulSoup | |
# need to capture a valid csrf token | |
# first visit the login page to generate one | |
s = requests.session() | |
response = s.get('https://callmeduele.com/login') | |
# extract the token | |
soup = BeautifulSoup(response.text) | |
for n in soup('input'): | |
if n['name'] == '_csrf_token': | |
token = n['value'] | |
break | |
# now post to that login page with some valid credentials and the token | |
auth = { | |
'userName': 'batman' | |
, 'password': 'j0kersuck5' | |
, '_csrf_token': token | |
} | |
s.post('https://callmeduele.com/login', data=auth) | |
# now we should be authenticated, try visiting a protected page | |
response = s.get('https://callmeduele.com/cases') | |
print response.text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Guys,
if you are using beautifulsoup4 4.3.2 then you should need to do some changes in the above code.
use from bs4 import BeautifulSoup instead of from BeautifulSoup import BeautifulSoup