Several ways of Python Requests using Cookie

This article will summarize several ways to use cookies in the interface request in the Python Requests library. The article uses the interface provided by the Postman official website to demonstrate https://postman-echo.com

1. Use the headers parameter

Use the cookie through the headers parameter, the key is Cookie, and the value is used; the concatenated cookie_name=cookie_value string

import requests

get_url = "https://postman-echo.com/get"
# key为Cookie,值为使用;拼接的 cookie_name=cookie_value 字符串
headers = {
    
    "Cookie":"cka=111a;ckb=111b"}

res = requests.get(url=get_url,headers=headers)

print(res.json().get("headers").get("cookie"))
print(res.request.headers.get("Cookie"))

The output is as follows:

cka=111a;ckb=111b
cka=111a;ckb=111b

2. Using cookies parameters

Use cookies through the cookies parameter, the cookies value is provided in the form of a dictionary, the key is cookie_name, and the value is cookie_value

import requests

get_url = "https://postman-echo.com/get"
# cookies 以字典形式提供,cookies 值以字典形式提供,key为cookie_name,value为cookie_value
cookies = {
    
    "cka":"222a","ckb":"222b"}

res = requests.get(url=get_url,cookies=cookies)

print(res.json().get("headers").get("cookie"))
print(res.request.headers.get("Cookie"))

output:

cka=222a; ckb=222b
cka=222a; ckb=222b

Note : When passing cookies through headers and cookies parameters at the same time, only the cookies passed by headers are valid.

3. Use through Session session

Through Session session management Cookie, multiple requests of the same session can share Cookie;
there are many ways to add Cookie in Session

Mode 0: Automatically set

During the session, if there is a set-cookie in the response header of the interface, it will be automatically added to the cookie of the session

import requests

session = requests.session()
print("会话初始cookie:",dict(session.cookies))

get_url = "https://postman-echo.com/get"
res = session.get(url=get_url)

print("响应头中set-cookie:",res.headers.get("set-cookie"))
print("会话现有cookie:",dict(session.cookies))

output:

会话初始cookie: {}
响应头中set-cookie: sails.sid=s%3ALo1-iQfueg8z1DhR_SX3KxwWA85cYN65.asZ1elFlT9g54uj%2FHkHpaZFkk0rBaCFDtRrA9anWzY4; Path=/; HttpOnly
会话现有cookie: {'sails.sid': 's%3ALo1-iQfueg8z1DhR_SX3KxwWA85cYN65.asZ1elFlT9g54uj%2FHkHpaZFkk0rBaCFDtRrA9anWzY4'}

Method 1: Set by key

Set the cookie directly through the key, but does not support setting the path, domain, etc. of the cookie

import requests

session = requests.session()
print("会话初始cookie:",dict(session.cookies))

# 直接通过key设置cookie,但不支持设置cookie的 path、domain 等值
session.cookies["cka"]="111a"
session.cookies["ckb"]="111b"

get_url = "https://postman-echo.com/get"
res = session.get(url=get_url)

print("本次请求使用的cookie:",res.request.headers.get("Cookie"))
print("会话现有cookie:",dict(session.cookies))

output:

会话初始cookie: {}
本次请求使用的cookie: cka=111a; ckb=111b
会话现有cookie: {'cka': '111a', 'ckb': '111b', 'sails.sid': 's%3AxtcEChogQfCYrRm9HDwAOFa4VlQQDsCZ.OR1TBpmuhX%2F2qI7mpTE0NdChrphD5AUcvcRqUF2y6NU'}

Method 2: set by the set method

Set the cookie through the set method, and support setting path, domain and other values

import requests

session = requests.session()
print("会话初始cookie:",dict(session.cookies))

# 通过set方法设置cookie,且支持设置path、domain等值
session.cookies.set("ck2","222",path="/",domain="postman-echo.com")

get_url = "https://postman-echo.com/get"
res = session.get(url=get_url)

print("本次请求使用的cookie:",res.request.headers.get("Cookie"))
print("会话现有cookie:",session.cookies)

output:

会话初始cookie: {}
本次请求使用的cookie: ck2=222
会话现有cookie: <RequestsCookieJar[<Cookie ck2=222 for postman-echo.com/>, <Cookie sails.sid=s%3AZW2JtlIjc1m9D2vVrn1Io57gVB6lVQiK.SjYcItCh92iqDkVF7oI8C6q5P8KmQ5DwB%2BiD4A6Ag48 for postman-echo.com/>]>

Note: <Cookie ck2=222 for postman-echo.com/>It can be seen that the set path and domain are successful

Method 3: Set by add_dict_to_cookiejar method

Set cookies through the add_dict_to_cookiejar method in the requests.utils toolkit, but does not support setting path, domain, etc.

import requests

session = requests.session()
print("会话初始cookie:",dict(session.cookies))

# 通过 requests.utils 工具包里的 add_dict_to_cookiejar 方法设置cookie,但不支持设置 path、domain 等值
cookie_dict = {
    
    "ck3a":"333a","ck3b":"333b"}
requests.utils.add_dict_to_cookiejar(session.cookies,cookie_dict=cookie_dict)

get_url = "https://postman-echo.com/get"
res = session.get(url=get_url)

print("本次请求使用的cookie:",res.request.headers.get("Cookie"))
print("会话现有cookie:",dict(session.cookies))

output:

会话初始cookie: {}
本次请求使用的cookie: ck3a=333a; ck3b=333b
会话现有cookie: {'ck3a': '333a', 'ck3b': '333b', 'sails.sid': 's%3AFY_7nq-hA_v9BxPaft4BHgRNiZOmDZ1S.N64IaIZ2Dd2fnfDMawbXdmJl0HfUVN7hhhGrdaFE4Bs'}

Method 4: Set via the RequestsCookieJar() object

Create an empty RequestsCookieJar() object, then use the set method of the object to assign a value, and then update to the current session cookie, which supports setting path, domain and other values

import requests

session = requests.session()
print("会话初始cookie:",dict(session.cookies))

# 创建一个空 RequestsCookieJar()对象,然后使用对象的set方法赋值,然后update更新到当前会话cookie,支持设置 path、domain等值
ckj = requests.sessions.RequestsCookieJar()
ckj.set('ck4a', '444a', path='/', domain='postman-echo.com')
session.cookies.update(ckj)

get_url = "https://postman-echo.com/get"
res = session.get(url=get_url)

print("本次请求使用的cookie:",res.request.headers.get("Cookie"))
print("会话现有cookie:",dict(session.cookies))

output:

会话初始cookie: {}
本次请求使用的cookie: ck4a=444a
会话现有cookie: {'ck4a': '444a', 'sails.sid': 's%3ANU88BiSVQAFpVUtrvSrii14jOhO_q981.MfJkY7Aw93R0Rc4V6JGi7SXPOneNJTr3p%2FNVJ9yp4Qg'}

Way 5: Set by cookiejar_from_dict method

Use the cookiejar_from_dict method in the requests.utils toolkit to convert the cookie in dictionary format to a cookiejar object, and then update to the current session. It does not support setting path, domain, etc.

import requests

session = requests.session()
print("会话初始cookie:",dict(session.cookies))

# 通过 requests.utils 工具包里的 cookiejar_from_dict 方法将字典格式的cookie转换为cookiejar对象,然后update更新到当前会话,不支持设置 path、domain 等值
cookie_dict = {
    
    "ck5a":"555a","ck5b":"555b"}
ckj5 = requests.utils.cookiejar_from_dict(cookie_dict=cookie_dict)
session.cookies.update(ckj5)

get_url = "https://postman-echo.com/get"
res = session.get(url=get_url)

print("本次请求使用的cookie:",res.request.headers.get("Cookie"))
print("会话现有cookie:",dict(session.cookies))

output:

会话初始cookie: {}
本次请求使用的cookie: ck5a=555a; ck5b=555b
会话现有cookie: {'ck5a': '555a', 'ck5b': '555b', 'sails.sid': 's%3AWHa__ab1vTZVjGdlIpDgDFfntSYNqS2Y.y%2Fq4YhPv49C5jwNiYdVWrFsQm9B0Y202rI5xRrqlwsk'}

おすすめ

転載: blog.csdn.net/B11050729/article/details/131293769