使用requests獲取並向headers中新增cookie

總侑刁民想害朕發表於2019-03-13
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'))

相關文章