使用requests获取并向headers中添加cookie

import requests
from requests.cookies import RequestsCookieJar


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
}
url = 'Target_URL'
res = requests.get(url, headers)
# print(res.cookies)

# 创建一个cookiejar实例
cookie_jar = RequestsCookieJar()
# 将获取的cookie转化为字典
resd = requests.utils.dict_from_cookiejar(res.cookies)
# 放开下面的,可查看cookie 的 key/value
# print(requests.utils.cookiejar_from_dict(resd))
# cookie_jar.set('cookie[key]', 'cookie[value]', domain='域名')
cookie_jar.set([key for key in resd][0], resd[[key for key in resd][0]], domain='www.123.com')

# 向请求头中添加cookie
res = requests.get(url, headers, cookies=cookie_jar)
print(res.status_code)
print(res.text.encode('utf-8', errors='ignore'))

你可能感兴趣的:(使用requests获取并向headers中添加cookie)