当前位置:   article > 正文

python (1) 获取cookie和使用cookie_python获取百度的repuest header里面的cookie

python获取百度的repuest header里面的cookie

获取cookie

方法一 requests.utils.dict_from_cookiejar()(推荐)

使用requests.utils.dict_from_cookiejar()把返回的cookies转换成字典

def get_cookie():
    url = "http://xxx"
    header = {
    	"Content-Type": "application/json; charset=UTF-8",
        "xxx": "xxx"
    }
    body = {
    	"xxx": "xxx", 
    	"xxx": "xxx"}
    try:
	    res = requests.post(url, headers=header, json=body, verify=False)
	    cookie = requests.utils.dict_from_cookiejar(res.cookies)
	    cookie = "c-token=" + cookie["c-token"]
	    return cookie
	except Exception as err:
        print('获取cookie失败:\n{0}'.format(err))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

方法二 遍历拼接

遍历cookies的键值,拼接成cookie格式

def get_cookie():
    url = "http://xxx"
    header = {
    	"Content-Type": "application/json; charset=UTF-8",
        "xxx": "xxx"
    }
    body = {
    	"xxx": "xxx", 
    	"xxx": "xxx"}
    try:
	    res = requests.post(url, headers=header, json=body, verify=False)
	    cookies = res.cookies.items()
        cookie = ''
        for name, value in cookies:
            cookie += '{0}={1};'.format(name, value)
        return cookie
    except Exception as err:    
        print('获取cookie失败:\n{0}'.format(err))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

使用cookie

方法一

import requests

def get_data():
    cookie = get_cookie()
    res = requests.get(url=xxxxx, cookies=cookie)
    print(res.text)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

比较简洁高效

方法二

import requests

def get_data():
    cookie = get_cookie()
    headers = {"cookie": cookie}
    res = requests.get(url=xxxxxx, headers=headers)
    print(res.text)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

更符合一般的表达习惯

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/384441
推荐阅读
相关标签
  

闽ICP备14008679号