Requests - 使用 Cookies
Requests - 处理 Cookie
Section titled “Requests - 处理 Cookie”HTTP cookies(Cookie)是服务器发送给用户网络浏览器的小块数据。浏览器存储这些 Cookie,并在后续请求中将它们发送回同一服务器。Cookie 被广泛用于会话管理(例如,保持用户登录状态)、个性化设置和追踪。Requests 库简化了在 Python 中处理 Cookie 的过程。
接收和检查 Cookie
Section titled “接收和检查 Cookie”当服务器在其响应中包含 Set-Cookie 头部时,Requests 会自动处理它们。这些 Cookie 存储在 response.cookies 属性中,这是一个 requests.cookies.RequestsCookieJar 对象。此对象的行为类似于字典。
我们使用 httpbin.org(一个用于测试 HTTP 请求的有用服务)来了解 Requests 如何处理服务器设置的 Cookie。
import requests
# This endpoint sets a cookie named 'my_cookie_name' with value 'my_cookie_value'# 这个端点会设置一个名为 'my_cookie_name'、值为 'my_cookie_value' 的 cookieurl_set_cookie = 'https://httpbin.org/cookies/set/my_cookie_name/my_cookie_value'
response = requests.get(url_set_cookie)
print('Cookies received from the server after initial set:')print('初次设置后从服务器接收到的 Cookie:')if response.cookies: for cookie_name, cookie_value in response.cookies.items(): print(f'- Name: {cookie_name}, Value: {cookie_value}')
# Access a specific cookie by name # 按名称访问特定 cookie if 'my_cookie_name' in response.cookies: print(f"Value of 'my_cookie_name': {response.cookies['my_cookie_name']}") print(f"'my_cookie_name' 的值: {response.cookies['my_cookie_name']}")else: print('No cookies were set or visible on the final response object.') print('最终响应对象上没有设置或可见的 Cookie。')
# Note: httpbin.org/cookies/set/... redirects. The cookie is set on the initial response,# which becomes part of response.history. The final response (after redirect) might not show it directly# in its .cookies attribute if the redirect is to a different path not sending cookies.# However, if using a Session, the cookie would be persisted and sent on subsequent requests to the domain.# 注意:httpbin.org/cookies/set/... 会发生重定向。Cookie 在初始响应上设置,# 该响应成为 response.history 的一部分。如果重定向到不发送 cookie 的不同路径,# 最终响应(重定向后)可能不会直接在其 .cookies 属性中显示该 cookie。# 但是,如果使用 Session,cookie 将被保留并发送到同一域的后续请求中。
# Let's verify by immediately asking httpbin what cookies it received (it won't see the one above without a session)# 我们立即向 httpbin 查询它接收到的 cookie 来进行验证(在没有 Session 的情况下,它不会看到上面的 cookie)check_url = 'https://httpbin.org/cookies'check_response_no_session = requests.get(check_url)print(f'\nCookies seen by {check_url} without session: {check_response_no_session.json()}')print(f'\n没有 Session 时,{check_url} 看到的 Cookie: {check_response_no_session.json()}')预期输出(根据 httpbin 行为可能略有不同):
Section titled “预期输出(根据 httpbin 行为可能略有不同):”Cookies received from the server after initial set:- Name: my_cookie_name, Value: my_cookie_valueValue of 'my_cookie_name': my_cookie_value
Cookies seen by https://httpbin.org/cookies without session: {'cookies': {}}初次设置后从服务器接收到的 Cookie:- Name: my_cookie_name, Value: my_cookie_value'my_cookie_name' 的值: my_cookie_value
没有 Session 时,https://httpbin.org/cookies 看到的 Cookie: {'cookies': {}}response.cookies 对象包含重定向链中最终响应的 Cookie。如果在重定向过程中较早的响应上设置了 Cookie,它们可能位于 response.history[i].cookies 中。Session 对象(稍后介绍)可以使这种管理变得透明。
发送自定义 Cookie
Section titled “发送自定义 Cookie”您可以通过将字典传递给请求函数(如 requests.get() 或 requests.post())的 cookies 参数来向服务器发送自己的 Cookie。
import requests
url_check_cookies = 'https://httpbin.org/cookies'custom_cookies_to_send = {'user_preference': 'dark_theme', 'language': 'en-US'}
response = requests.get(url_check_cookies, cookies=custom_cookies_to_send)
print('Server received the following custom cookies:')print('服务器收到了以下自定义 Cookie:')print(response.json()) # httpbin.org/cookies returns a JSON of cookies it received # httpbin.org/cookies 返回它接收到的 Cookie 的 JSONServer received the following custom cookies:{ 'cookies': { 'language': 'en-US', 'user_preference': 'dark_theme' }}服务器收到了以下自定义 Cookie:{ 'cookies': { 'language': 'en-US', 'user_preference': 'dark_theme' }}使用 Session 对象保持 Cookie
Section titled “使用 Session 对象保持 Cookie”对于需要在多个请求之间保持 Cookie 的场景(例如,维护登录会话、跟踪偏好设置),requests.Session 对象是理想的解决方案。Session 对象会自动管理 Cookie:服务器设置的任何 Cookie 都会存储在会话中,并在后续请求中发送到同一域。
import requests
# Create a Session object. It's good practice to use it as a context manager.# 创建一个 Session 对象。建议将其用作上下文管理器。with requests.Session() as session: # First, let the server set a cookie within this session # 首先,让服务器在此会话中设置一个 cookie # This endpoint will set 'session_cookie_key' to 'session_cookie_value' # 这个端点会将 'session_cookie_key' 设置为 'session_cookie_value' session.get('https://httpbin.org/cookies/set/session_cookie_key/session_cookie_value') print("A session cookie should now be set internally by the session object.") print("会话对象现在应该已经在内部设置了一个会话 cookie。")
# Now, make another request to an endpoint that shows received cookies. # 现在,向一个显示接收到 cookie 的端点发出另一个请求。 # The session will automatically send the cookie it received earlier. # 会话将自动发送它之前接收到的 cookie。 response_with_session_cookie = session.get('https://httpbin.org/cookies')
print('\nCookies sent by the session and received by httpbin.org/cookies:') print('\n会话发送并被 httpbin.org/cookies 接收到的 Cookie:') received_cookies_data = response_with_session_cookie.json() print(received_cookies_data)
if 'session_cookie_key' in received_cookies_data.get('cookies', {}): value = received_cookies_data['cookies']['session_cookie_key'] print(f"Successfully received 'session_cookie_key' with value: {value}") print(f"成功接收到 'session_cookie_key',值为: {value}")A session cookie should now be set internally by the session object.
Cookies sent by the session and received by httpbin.org/cookies:{ 'cookies': { 'session_cookie_key': 'session_cookie_value' }}Successfully received 'session_cookie_key' with value: session_cookie_value会话对象现在应该已经在内部设置了一个会话 cookie。
会话发送并被 httpbin.org/cookies 接收到的 Cookie:{ 'cookies': { 'session_cookie_key': 'session_cookie_value' }}成功接收到 'session_cookie_key',值为: session_cookie_value使用 Session 对象是处理依赖于 Cookie 的有状态交互(如登录或多步流程)的推荐方法。
在浏览器中检查 Cookie(作为参考)
Section titled “在浏览器中检查 Cookie(作为参考)”虽然与 Requests 库没有直接关系,但了解如何在网络浏览器中查看 Cookie 会很有帮助。您通常可以使用浏览器的开发者工具(通常按 F12 键访问)检查 Cookie。查找诸如“Application”(在 Chrome/Edge 中)、“Storage”(在 Firefox 中)等选项卡,或检查“Network”选项卡中的单个请求,以查看 Set-Cookie(响应头部)和 Cookie(请求头部)。
熟练掌握 Requests 中的 Cookie 处理对于有效的网页抓取、API 交互和自动化基于网络的任务至关重要。