파이썬 쿠키
1. 쿠키세트를 통으로 세팅
방법 1)
[code]
import requests
session = requests.session()
my_cookies = {
‘cookie_key’: ‘cookie_value’,
‘another_cookie_key’: ‘another_cookie_value’
}
requests.utils.add_dict_to_cookiejar(session.cookies, my_cookies)
[/code]
방법 2)
[code]
my_cookies = {
‘cookie_key’: ‘cookie_value’,
‘another_cookie_key’: ‘another_cookie_value’
}
session = requests.session()
session.cookies.update(my_cookies)
[/code]
2. 쿠키 한개 세팅
방법 1)
[code]
import requests
s = requests.session()
s.cookies.set(“COOKIE_NAME”, “the cookie works”, domain=”example.com”)
[/code]
방법 2)
[code]
import requests
s = requests.session()
# domain 은 옵션이다
cookie_obj = requests.cookies.create_cookie(domain=”example.com”,name=”COOKIE_NAME”,value=”the cookie works”)
s.cookies.set_cookie(cookie_obj)
[/code]
방법 3)
[code]
required_args = {
‘name’: ‘COOKIE_NAME’,
‘value’: ‘the cookie works’
}
optional_args = {
‘domain’:’example.com’,
‘path’:’/’,
‘secure’:False,
‘expires’:None,
‘discard’:True,
‘comment’:None,
‘comment_url’:None,
‘rest’:{‘HttpOnly’: None},
‘rfc2109’:False
}
my_cookie = requests.cookies.create_cookie(**required_args, **optional_args)
s = requests.session()
s.cookies.set_cookie(my_cookie)
[/code]
3. 쿠키를 파일에 저장
[code]
import pickle
cookies = response.cookies.get_dict()
with open(‘data.pkl’, ‘wb’) as f:
pickle.dump(cookies, f)
[/code]
4. 파일의 내용을 쿠키에 세팅
[code]
with open(‘data.pkl’, ‘rb’) as f:
cookies = pickle.load(f)
session = requests.session()
session.cookies.update(cookies)
[/code]