Home  >  Article  >  Backend Development  >  How to Extract Cookies After Logging into a Webpage with Python?

How to Extract Cookies After Logging into a Webpage with Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 06:05:29958browse

How to Extract Cookies After Logging into a Webpage with Python?

Logging into a Webpage and Extracting Cookies for Subsequent Use in Python

To access a webpage that requires authentication, it is necessary to obtain the cookies set during the login process. This article outlines a method to log into a webpage using Python 2.6 and retrieve the cookies for later use.

Utilizing the requests library, the following code snippet demonstrates how to achieve this:

<code class="python">from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)</code>

This script establishes a session with the website, logs in by sending the POST parameters, and then performs a request to a protected page. The session object automatically handles cookie management, so the cookies obtained during the login process will be used in subsequent requests.

This approach is convenient and straightforward, and it allows for easy retrieval and utilization of cookies without the need for complex cookie manipulation mechanisms.

The above is the detailed content of How to Extract Cookies After Logging into a Webpage with Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn