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

Ft 2020-09-16 PM 132℃ 0条
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'))
您的大名:
万水千山总是情,给个打赏行不行。 打赏
标签: python

非特殊说明,本博所有文章均为博主原创。

评论啦~