automate login in python

To automate login using python, you can use the requests library to send HTTP requests and BeautifulSoup library to parse HTML responses. Here's a simple example to get you started:

main.py
import requests
from bs4 import BeautifulSoup

# Login details
username = 'your_username'
password = 'your_password'

# URL of the login page
login_url = 'https://example.com/login'

# Create a session
session = requests.Session()

# Get the login page HTML content
login_page = session.get(login_url).content

# Parse HTML content to get form details
soup = BeautifulSoup(login_page, 'html.parser')
form = soup.find('form')
inputs = form.findAll('input')

# Get form action URL
action_url = form['action']

# Fill in form data
form_data = {input_tag['name']: input_tag['value'] for input_tag in inputs}
form_data['username'] = username
form_data['password'] = password

# Submit the login form
session.post(action_url, data=form_data)

# Check if login successful
dashboard_url = 'https://example.com/dashboard'
dashboard_page = session.get(dashboard_url).content
if 'Welcome, {}'.format(username) in dashboard_page:
    print('Login successful')
else:
    print('Login failed')
980 chars
40 lines

In this example, we first create a session using requests.Session(). Then we get the login page HTML content using session.get(login_url).content and parse it using BeautifulSoup. We extract the form details from the HTML content and fill in our login details in the form data. Finally, we submit the login form using session.post(action_url, data=form_data) and check if login was successful by navigating to the dashboard page and searching for a welcome message with the username.

gistlibby LogSnag