For this example, we are going to log in to a Django application. If it is another type of application, you only have to check the needed login form fields.
import requests from bs4 import BeautifulSoup USERNAME = 'username' # put correct username here PASSWORD = 'password' # put correct password here URL = 'https://your.url.com' # Change to your domain LOGINURL = URL + '/login/' # Change to your app login url DATAURL = URL + 'url_data' # Change session = requests.session() req_headers = { 'Content-Type': 'application/x-www-form-urlencoded' } # to get csrfToken r = session.get(LOGINURL, headers=req_headers, allow_redirects=False) soup = BeautifulSoup(r.text) csrfToken = soup.find('input', attrs={'name': 'csrf_token'})['value'] formdata = { 'username': USERNAME, 'password': PASSWORD, 'csrf_token': csrfToken, } # login post r = session.post(LOGINURL, data=formdata, headers=req_headers, allow_redirects=False) # We are logged in and we can read data r2 = session.get(DATAURL)
One thought on “How to programmatically log in to website App using Python”