python如何获取cookie

来源:千锋教育
发布时间:2023-11-09 17:05:47
分享

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

(1)借助handler

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

fromhttpimportcookiejar

fromurllibimportrequest

classCraw():

def__init__(self):

self.url=''

self.headers['User-Agent']='Mozilla/5.0(WindowsNT6.3;Win64;x64)'\

'AppleWebKit/537.36(KHTML,likeGecko)Chrome/65.0.3325.162Safari/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=''

foritemincookie:

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)

returnbase64_jpg

(2)使用responseheaders的set_cookie

importrequests

importre

classCrawler():

defgetCookie(self):

response=requests.post(self.url)

set_cookie=response.headers['Set-Cookie']

array=re.split('[;,]',set_cookie)

cookieValue=''

forarrinarray:

ifarr.find('DZSW_SESSIONID')>=0orarr.find('bl0gm1HBTB')>=0:

cookieValue+=arr+';'

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

只写getCookies方法,代码如下:

importrequests

classCrawler():

defgetCookie(self):

response=requests.get(self.url)

cookie_value=''

forkey,valueinresponse.cookies.items():

cookie_value+=key+'='+value+';'

self.headers['Cookie']=cookie_value

以上内容为大家介绍了python培训之如何获取cookie,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

声明:本站部分稿件版权来源于网络,如有侵犯版权,请及时联系我们。

相关推荐

  • python能判断对象的类型吗 判断python中的对象类型,可以使用isinstance()函数。isinstance是Python中的一个内建函数。是用来判断一个对象的变量类型。函数语法格式为isinstance(object,
  • python如何判断对象是否有某个属性 python如何判断某一对象是否有某一属性,可以使用hasattr函数。hasattr(object,name)说明:判断对象object是否包含名为name的特性(hasattr是通过调用getat
  • pythonpython是什么类型的语言 python是一种面向对象、解释型、动态类型计算机程序设计语言。1.解释型:程序无需编译成二进制代码,而是在执行时对语句一条一条编译;2.动态类型:在程序执行过程中,可以改变变量的类型;它常被昵称为胶
  • pythonurllib怎么用 在python3中,urllib和urllib2进行了合并,现在只有一个urllib模块,urllib和urllib2的中的内容整合进了urllib.request,urlparse整合进了urlli
  • python脚本语言 Python是一种计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越来越多被用于独立的、大型项目的开发。同时Pyth
  • python什么是格式化 本文总结一下python格式化文本的方法,需要的小伙伴可以参考。1、首先看使用%格式化文本常见的占位符:常见的占位符有:%d整数%f浮点数%s字符串%x十六进制整数使用方法>>>'Hello,