python获取cookie的方法

摘要:
介绍下3种获取cookie的方法。已尝试,结果报错,最后还是使用的方法2。希望熟悉的大神看到可以给予解答。

介绍下3种获取cookie的方法。

(1)借助handler

这种方法也是网上介绍最多的一种方法,但是用起来比较麻

fromhttpimportcookiejar
from
urllib importrequest classCraw(): def __init__(self): self.url = '' self.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36' self.headers['Content-Type'] = 'application/x-www-form-urlencoded' defgetCookies(self): cookie =cookiejar.CookieJar() handler =request.HTTPCookieProcessor(cookie) opener =request.build_opener(handler) response =opener.open(self.url) cookieValue = '' for item incookie: cookieValue += item.name + '=' + item.value + ';' self.headers['Cookie'] =cookieValue response = requests.get(url=self.url) defgetVerificationCode(self):
img_url = ''
imgResponse = requests.get(url=img_url,headers =self.headers) #直接使用headers即可 base64_jpg =base64.b64encode(imgResponse.content) return base64_jpg

(2)使用response headers的set_cookie

import requests
import re
classCrawler():
  def getCookie(self):
response = requests.post(self.url)
set_cookie = response.headers['Set-Cookie']
    array = re.split('[;,]',set_cookie)
    cookieValue = ''
    for arr in array:
      if arr.find('DZSW_SESSIONID') >= 0 or arr.find('bl0gm1HBTB') >= 0:
        cookieValue += arr + ';'

(3)使用response的cookies属性获取

只写getCookies方法,代码如下:

importrequests    
classCrawler():
    defgetCookie(self):
        response =requests.get(self.url)
        cookie_value = ''
        for key,value inresponse.cookies.items():  
            cookie_value += key + '=' + value + ';'
        self.headers['Cookie'] = cookie_value

另外还有个疑问,就是response.cookies返回的是RequestsCookieJar对象,看到书上有这样的代码

importrequests
classCrawl():
    def __init__(self):
        self.url = ''
        self.headers ={}
        self.cookieJar =requests.cookies.RequestsCookieJar()
    defgetCookie()
        cookies = 'a=a1;b=b1' #字符串
        for cookie in cookies.split(';'):
            key,value = cookie.split('=,1)
self.cookieJar.set(key,value)
        r = requests.get(self.url,cookies = self.cookieJar,headers = self.headers)
为什么不可以直接使用response.cookies赋值给最后请求的cookies。已尝试,结果报错,最后还是使用的方法2。

希望熟悉的大神看到可以给予解答。

免责声明:文章转载自《python获取cookie的方法》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇kettle连接DM7(达梦7)数据库基于windows server 2012 的微软桌面虚拟化实战教程下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

python- 双层装饰器 字符串格式化 python模块 递归 生成器 迭代器 序列化

1.双层装饰器 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # author:zml LOGIN_INFO=False IS_ADMIN=False defcheck_log(func): definner(): res=func() ifLOGIN_INFO: print('验证成功!') return...

记一次 synchronized 锁字符串引发的坑兼再谈 Java 字符串

业务有一个需求,我把问题描述一下: 通过代理IP访问国外某网站N,每个IP对应一个固定的网站N的COOKIE,COOKIE有失效时间。 并发下,取IP是有一定策略的,取到IP之后拿IP对应的COOKIE,发现COOKIE超过失效时间,则调用脚本访问网站N获取一次数据。 为了防止多线程取到同一个IP,同时发现该IP对应的COOKIE失效,同时去调用脚本更新...

PyQt(Python+Qt)学习随笔:QTreeWidgetItem项下子项的指示符展示原则childIndicatorPolicy

老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 树型部件QTreeWidget中的QTreeWidgetItem项下可以有子项,如果存在子项,则父项的节点是否显示展开或折叠子项的提示符由属性childIndicatorPolicy控制。 childIndicatorPolicy属性的类型为枚举类型QT...

创建指定python版本的虚拟环境

使用virtualenvwrapper管理虚拟环境   鉴于virtualenv不便于对虚拟环境集中管理,所以推荐直接使用virtualenvwrapper。 virtualenvwrapper提供了一系列命令使得和虚拟环境工作变得便利。它把你所有的虚拟环境都放在一个地方。 1.安装virtualenvwrapper(确保virtualenv已安装)...

python|sqlalchemy|联表查询

2020-04-20|待完善,给出可以直接运行的py文件 建立表的类 class Account(db.Model): __tablename__ = 'account' id = db.Column(db.INT, primary_key=True, nullable=False, autoincrement=True) nick...

Python面向对象之反射

一、补充 @classmethod 整个方法中没有用到对象命名空间中的名字,且用到了类的命名空间中的名字(普通方法和属性property除外) 类方法的默认参数:cls 调用这个发方法的类 类方法的调用方式:通过类名调用 通过类名调用的本质是方法 @statimethod 将一个普通函数放到类中来就给这个函数加一个@staticmethod装饰器 这个函...