requests请求返回 set_cookie的处理,CookieJar转字典

1. 登录返回set_cook,把 新cook值 添加到 cookie 中

from http.cookies import SimpleCookie

result = requests.post(url=url_limit, headers=headers, data=data, verify=False)
# 设置cookie
if 'Set-Cookie' in result.headers:
	simple_cookie = SimpleCookie(result.headers['Set-Cookie'])
	print(f'simple_cookie is {simple_cookie}')
	for item in simple_cookie:
	    cook = cook + '; ' + item + "=" + simple_cookie[item].value
	print(f'r_2 headers is {headers}')
	r_2 = requests.post(url=url_check, headers=headers, data=data, verify=False)
	print(f'r_2 is {r_2.content}')
else:
	print(result.content)

1.cook转化操作

  • 将CookieJar转为字典:
cookies = requests.utils.dict_from_cookiejar(r.cookies)
  • 将字典转为CookieJar:
cookiejar = requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)
#其中cookie_dict是要转换字典
  • 转换完之后就可以把它赋给cookies 并传入到session中了:
s = requests.Session()
s.cookies = cookies

1.requests请求带cook

import requests

url = "http://www.renren.com/967272361/profile"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
}

# 不带上Cookie就访问不了这个页面
cookie = "anonymid=jk63khrk-y97r4p; _r01_=1; ln_uact=mr_mao_hacker@163.com; ln_hurl=http://hdn.xnimg.cn/photos/hdn421/20180720/1740/main_JAWQ_0aa000000ceb195a.jpg; _ga=GA1.2.273332130.1532825428; depovince=HUN; JSESSIONID=abcE5k0CiAJDc9ESVEcuw; ick_login=026ba348-e4e9-4871-9ce3-5868b95cfdd3; first_login_flag=1; loginfrom=syshome; wp_fold=0; BAIDU_SSP_lcr=https://www.baidu.com/link?url=VRx_HKUd53I5rYWZHvrQ9VVLotqST6-jtaZDlscFYCO&wd=&eqid=e957aec400037928000000065b64fcab; ick=64518f30-9a22-47df-b3c3-4114f185c3c6; t=8fcf47068763c279eea2620b51b7a3311;"

# 将上面那个cookie转化成字典类型
cookie_dict = {i.split("=", 1)[0]:i.split("=", 1)[-1] for i in cookie.split("; ")}
# 传参数cookies为 {}字典 格式
response = requests.get(url, headers = headers, cookies = cookie_dict)

2.APP请求请求头

import requests
import time
import uuid


class PC_APP():
    def __init__(self):
        # 设备号
        self.device_id = uuid.uuid4().hex
        time_stamp = time.strftime("%Y-%m-%d'T'%H:%M:%S", time.localtime())
        self.headers = {
            'X-TIMESTAMP': time_stamp,
            'Accept-Language': 'en',
            'X-PLATFORM': 'android',
            'X-VERSION': '2.24.0',
            'X-FLOW-TYPE': 'OTHER',
            'X-SYSTEM-VERSION': '9',
            'X-DEVICE-ID': self.device_id,
            'Content-Type': 'application/json; charset=UTF-8',
            'Connection': 'Keep-Alive',
            'Accept-Encoding': 'gzip',
            'User-Agent': 'okhttp/3.12.6'
        }
        self.session = requests.session()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值