Session Management With Proxies in Python: Cookies, Persistence, and Sticky IPs
Introduction
Session management is crucial for web scraping and automation tasks, especially when dealing with sites that require authentication or maintain state across requests. In this guide, we'll dive into practical techniques for managing sessions with proxies in Python using the requests library. We'll cover cookie persistence, sticky IP sessions, session serialization, and handling session expiry.
Cookie Persistence
When scraping websites, maintaining cookies is essential to preserve user state, such as login credentials or session tokens. The requests.Session object automatically handles cookies for you, making it easy to persist them across requests.
Example: Basic Session with Cookies
import requests
# Create a new session
session = requests.Session()
# Login request
login_url = 'https://example.com/login'
payload = {'username': 'user', 'password': 'pass'}
response = session.post(login_url, data=payload)
# Check if login was successful
if response.ok:
# Now you can make other requests with the same session
profile_response = session.get('https://example.com/profile')
print(profile_response.text)
Managing Cookies with `MozillaCookieJar`
For more control over cookies, especially when dealing with complex cookie structures or external cookie files (like those from a browser), you can use MozillaCookieJar.
from requests.cookies import MozillaCookieJar
# Create a session
session = requests.Session()
# Load cookies from a file
cookie_jar = MozillaCookieJar('cookies.txt')
cookie_jar.load(ignore_discard=True, ignore_expires=True)
session.cookies.update(cookie_jar)
# Make a request with the loaded cookies
response = session.get('https://example.com/protected')
print(response.text)
Sticky IP Sessions
Some websites enforce strict IP-based restrictions, requiring you to use the same IP address throughout a session. Managed proxy services like Bright Data and SmartProxy offer sticky sessions that keep your requests coming from the same IP.
Example: Using SmartProxy for Sticky IPs
SmartProxy provides a session parameter in their API to maintain sticky sessions.
import requests
# Proxy configuration
proxies = {
'http': 'http://user:[email protected]:port?session=your-session-id',
'https': 'https://user:[email protected]:port?session=your-session-id'
}
# Create a session
session = requests.Session()
session.proxies.update(proxies)
# Make requests using the sticky IP session
response1 = session.get('https://example.com/step1')
response2 = session.get('https://example.com/step2')
print(response1.text)
print(response2.text)
Example: Using Bright Data for Sticky IPs
Bright Data uses zones to enforce sticky sessions. You can specify a zone in your proxy URL.
import requests
# Proxy configuration
proxies = {
'http': 'http://user:[email protected]:port?zone=your-zone',
'https': 'https://user:[email protected]:port?zone=your-zone'
}
# Create a session
session = requests.Session()
session.proxies.update(proxies)
# Make requests using the sticky IP session
response1 = session.get('https://example.com/step1')
response2 = session.get('https://example.com/step2')
print(response1.text)
print(response2.text)
Session Serialization
For long-running scraping tasks, it's useful to serialize your sessions to disk so you can resume them later without losing state.
Example: Serializing and Deserializing Sessions with `pickle`
import pickle
import requests
# Function to save a session to disk
def save_session(session, filename):
with open(filename, 'wb') as f:
pickle.dump(requests.Session.__dict__, f)
# Function to load a session from disk
def load_session(filename):
with open(filename, 'rb') as f:
data = pickle.load(f)
session = requests.Session()
session.__setstate__(data)
return session
# Create and save a session
session = requests.Session()
login_url = 'https://example.com/login'
payload = {'username': 'user', 'password': 'pass'}
response = session.post(login_url, data=payload)
save_session(session, 'my_session.pkl')
# Load the session later
loaded_session = load_session('my_session.pkl')
profile_response = loaded_session.get('https://example.com/profile')
print(profile_response.text)
Note: Be cautious with serialization of sensitive information like API keys or passwords.
Detecting Session Expiry and Re-auth Logic
Handling session expiry is critical to ensure your scraping tasks continue uninterrupted. Typically, this involves detecting a redirect back to the login page (HTTP 302) and re-authenticating.
Example: Handling Session Expiry
import requests
# Create a session
session = requests.Session()
def authenticate(session):
login_url = 'https://example.com/login'
payload = {'username': 'user', 'password': 'pass'}
response = session.post(login_url, data=payload)
return response.ok
# Initial authentication
if not authenticate(session):
print("Initial authentication failed.")
else:
# Navigate and extract data
profile_response = session.get('https://example.com/profile')
if profile_response.status_code == 302: # Redirect indicates session expiry
if authenticate(session): # Re-authenticate
profile_response = session.get('https://example.com/profile')
print(profile_response.text)
else:
print("Re-authentication failed.")
else:
print(profile_response.text)
Conclusion
Managing sessions with proxies in Python is essential for robust web scraping and automation tasks. By using requests.Session, managing cookies, leveraging sticky IP services like SmartProxy or Bright Data, serializing sessions, and handling session expiry, you can maintain a persistent and reliable scraping environment.
If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download
Free proxies break. ProxyForge doesn't.
The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.
Download ProxyForge free →