Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Requests session() Method



The Python Requestssession() method creates a persistent session for making HTTP requests allowing us to reuse parameters like cookies and headers across multiple requests within the same session. This enhances performance by maintaining a connection pool and efficiently handling cookies and authentication.

Additionally, it persists headers and other settings between requests like connection timeouts. By persisting state across requests,requests.session() streamlines web scraping, API interaction and other tasks requiring repeated HTTP requests while providing a convenient interface for managing session-specific data and settings.

It's particularly useful for scenarios where efficiency and state management are crucial such as web automation or API integration.

Syntax

Following is the syntax and parameters of Python Requestssession() method −

requests.session()

Parameter

This method does not take any parameters.

Return value

This method returns a Response object.

Example 1

Following is the basic example of the python requestssession() method −

import requests# Create a sessionsession = requests.session()# Now you can use `session` to make requestsresponse = session.get('https://google.com')print(response)

Output

<Response [200]>

Example 2

When making HTTP requests using the requests library in Python we can preserve cookies across multiple requests by utilizing a session object. A session object will persist cookies across all requests within that session. Here's how we can do it −

import requests# Create a session objectsession = requests.Session()# Perform a GET request to receive cookiesresponse = session.get('https://tutorialspoint.com')# Print the received cookiesprint("Received cookies:", session.cookies)# Now, you can make subsequent requests within the same sessionresponse = session.get('https://tutorialspoint.com/another-page')# Print the updated cookies after subsequent requestsprint("Updated cookies:", session.cookies)

Output

Received cookies: <RequestsCookieJar[]>Updated cookies: <RequestsCookieJar[]>>

Example 3

Setting headers in HTTP requests using the requests library in Python is straightforward. We can pass a dictionary containing the headers to the headers parameter of the request methods such as get, post, put, delete, etc. Below is an example of how we can set headers −

import requests# Define custom headersheaders = {    'User-Agent': 'Welcome to tutorialspoint',    'Authorization': 'Bearer my_token'}# Make a GET request with custom headersresponse = requests.get('https://tutorialspoint.com', headers=headers)# Print the responseprint(response.text)

Output

<!DOCTYPE html>><html lang="en">---------------------------------------------------------</script></body></html></pre>
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp