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

How to disable cookie handling with the Python requests library?

1个答案

1

When using the requests library in Python for network requests, it automatically handles and stores cookies by default. If you have specific requirements that necessitate disabling automatic cookie handling, you can achieve this through several methods.

Method One: Using Session Object and Modifying Its Configuration

In requests, you can use the Session object and modify its settings to disable automatic cookie handling. The steps are as follows:

python
import requests # Create a Session object session = requests.Session() # Disable automatic cookie handling session.cookies.set_policy(requests.cookies.DefaultCookiePolicy(blocked_domains=["*"])) # Send a request using the updated session response = session.get('http://example.com') print(response.text)

Here, by setting blocked_domains to a list containing all domains, any automatic cookie handling is blocked.

Method Two: Not Using Session, Directly Manipulating Requests

If you prefer not to use the Session object, you can directly manipulate each request. By not providing cookies when sending requests, you can effectively disable cookie handling. For example:

python
import requests # Send a request without providing any cookies response = requests.get('http://example.com', cookies={}) print(response.text)

Here, even if the server attempts to set cookies, requests will not save them because we are not providing a storage location.

Summary

Both methods can effectively disable automatic cookie handling when using the requests library in Python. The choice depends on your specific needs, such as whether you need to manage multiple requests uniformly (using Session) or control each independent request individually. Both methods are effective and can be chosen based on your specific situation.

2024年8月12日 14:16 回复

你的答案