赞
踩
网上描述一大堆,此处不在赘述;
大家知道有些链接在请求时,需要携带cookie字段,而这些cookie字段部分需要从某些响应头里获取(另一部分通过抓包或者js获取),提取后再添加到下一个url的请求中。这样就很麻烦;使用session的好处是:使用session则可以将响应头的cookie自动放入RequestsCookieJar,在下次请求时会自动携带。
我们通过代码查看如下:
def china_189_session(): """session test""" session = requests.session() response = session.post(url='http://189.cn/dqmh/system.do?operate=index', headers={ "Host": "189.cn", "Origin": "http://189.cn", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36", "DNT": "1", "Accept": "*/*", "Referer": "http://189.cn/", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9" } ) print(response.status_code) print(response.headers.get('Set-Cookie')) print(session.cookies) print('\n') url = 'https://kxlogo.knet.cn/seallogo.dll?sn=e12050811010020422307708&size=0' response = session.get(url=url, headers={ "Host": "kxlogo.knet.cn", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36", "Accept": "*/*", "DNT": "1", "Referer": "http://189.cn/", "Sec-Fetch-Site": "cross-site", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9" }) print(response.status_code) print(response.headers.get('Set-Cookie')) print(session.cookies) """ 运行输出: 200 JSESSIONID-JT=D1F5BD024D997F7E9ACE1F3EB74113FF-n3; Path=/; HttpOnly, dqmhIpCityInfos=%E4%B8%8A%E6%B5%B7%E5%B8%82+%E8%81%94%E9%80%9A; Domain=.189.cn; Expires=Wed, 27-Nov-2019 03:49:33 GMT; Path=/ <RequestsCookieJar[<Cookie dqmhIpCityInfos=%E4%B8%8A%E6%B5%B7%E5%B8%82+%E8%81%94%E9%80%9A for .189.cn/>, <Cookie JSESSIONID-JT=D1F5BD024D997F7E9ACE1F3EB74113FF-n3 for 189.cn/>]> 200 KXUUID="672b9b94cIRHA/rtpg/mzKRY0Xf4hx4IgeF8reK822M68dHjxGc="; Version=1; Domain=.knet.cn; Max-Age=2147483646; Expires=Sat, 15-Nov-2087 07:03:39 GMT; Path=/ <RequestsCookieJar[<Cookie dqmhIpCityInfos=%E4%B8%8A%E6%B5%B7%E5%B8%82+%E8%81%94%E9%80%9A for .189.cn/>, <Cookie KXUUID="672b9b94cIRHA/rtpg/mzKRY0Xf4hx4IgeF8reK822M68dHjxGc=" for .knet.cn/>, <Cookie JSESSIONID-JT=D1F5BD024D997F7E9ACE1F3EB74113FF-n3 for 189.cn/>]> """
另外: 附带 RequestsCookieJar 和cookies格式的相互转换方法
def getCurrCookie(cookiejar): ''' cookiejar 转为字典 :param cookies:cookiejar (self.session.cookies) :return: cookie:dict ''' cookie = requests.utils.dict_from_cookiejar(cookiejar) return cookie def cookie_from_session(cookie): """ cookie 添加到session :param cookie: dict json :return: """ cookie_dict = json.loads(cookie) for k, v in cookie_dict.items(): session.cookies.set(k, v) # 向session中单独添加某个cookie字段 可使用update 如添加 'login_account=1' self.session.cookies.update({'login_account': '1'})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。