Select a Subtopic
Let's dive into Day 7: Handling Cookies for Persistent Login (Selenium)
Day 7: Handling Cookies for Persistent Login (Selenium)
Concepts to Learn Today
- How to save cookies after logging in.
- How to reuse saved cookies to skip login in future sessions.
- Methods like
get_cookies()
,add_cookie()
, anddelete_cookie()
.
Why Handle Cookies?
Instagram detects automated logins and blocks bots. Saving and reusing cookies allows your bot to stay logged in without triggering Instagram’s anti-bot mechanisms.
Practical Task: Automate Instagram Login with Cookie Persistence
Step 1: Install Required Libraries
# Install required libraries
pip install selenium
Step 2: Code to Save Cookies After Login
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import time
import pickle
# Path to your ChromeDriver
service = Service("path/to/chromedriver")
# Initialize WebDriver
driver = webdriver.Chrome(service=service)
driver.get("https://www.instagram.com/")
# Wait for elements to load
time.sleep(5)
# Log in to Instagram (Replace with your credentials)
username = driver.find_element(By.NAME, "username")
password = driver.find_element(By.NAME, "password")
login_button = driver.find_element(By.XPATH, "//button[@type='submit']")
username.send_keys("your_username")
password.send_keys("your_password")
login_button.click()
# Wait for login to complete
time.sleep(10)
# Save cookies to a file
with open("cookies.pkl", "wb") as file:
pickle.dump(driver.get_cookies(), file)
print("Cookies saved!")
driver.quit()
Step 3: Code to Load Cookies and Skip Login
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import time
import pickle
# Path to your ChromeDriver
service = Service("path/to/chromedriver")
# Initialize WebDriver
driver = webdriver.Chrome(service=service)
driver.get("https://www.instagram.com/")
# Load cookies from the file
with open("cookies.pkl", "rb") as file:
cookies = pickle.load(file)
# Add cookies to the browser
for cookie in cookies:
driver.add_cookie(cookie)
# Refresh the page to apply cookies
driver.refresh()
# Verify if logged in successfully
time.sleep(5)
print("Logged in using cookies!")
Explanation
- Saving Cookies: After logging in, we save the session cookies using
driver.get_cookies()
andpickle.dump()
. - Loading Cookies: We load the saved cookies using
pickle.load()
and usedriver.add_cookie()
to apply them to the session. - Refreshing the Page: After adding the cookies, refreshing the page automatically logs in without entering credentials.
Final Challenge for Day 7
- Create a bot that logs in to Instagram, saves cookies, and reuses cookies to log in automatically.
- Bonus: Handle cases where cookies expire and prompt the bot to log in again.
Would you like a GitHub repository with this project?