乐闻世界logo
搜索文章和话题

How can I use cookies in Python Requests?

1个答案

1

Using Cookies in Python is primarily achieved through the requests library. requests is a widely adopted HTTP library for sending various HTTP requests. There are two primary approaches for using Cookies: manually setting Cookies or using a Session to automatically manage Cookies.

Manually Setting Cookies

When you know the Cookies to set, you can manually include them in the request. Here is an example:

python
import requests url = 'http://example.com/data' cookies = {'user_session': '123456789abcdef'} response = requests.get(url, cookies=cookies) print(response.text)

In this example, we create a dictionary named cookies containing the Cookies to send. Then, we pass this dictionary to the cookies parameter in the requests.get() function. As a result, the HTTP request will include these Cookies when sent.

Using Session to Automatically Manage Cookies

Using requests.Session() automatically manages Cookies, which is highly useful when handling multiple requests, especially during login and session maintenance. The Session object maintains Cookies across all requests, enabling multiple requests within the same session without re-sending Cookies. Here is an example:

python
import requests # Create a Session object session = requests.Session() # First, perform login; assume the server sets Cookies upon successful login login_url = 'http://example.com/login' credentials = {'username': 'user', 'password': 'pass'} session.post(login_url, data=credentials) # Now use the same session object to send other requests; Cookies will be automatically managed data_url = 'http://example.com/data' response = session.get(data_url) print(response.text)

In this example, we first send a POST request with login credentials. Assuming the server sets Cookies upon successful login, the Session object automatically sends these Cookies in subsequent requests. This allows users to access pages requiring authentication.

Summary

Using Cookies is a common requirement in web development, particularly for handling login and session management. With the requests library, Python simplifies using Cookies through manual setting or Session usage.

2024年7月23日 12:50 回复

你的答案