导语:
本文主要介绍了关于python如何获取cookie的相关知识,包括html页面获取cookie,以及python获取cookies过期时间这些编程知识,希望对大家有参考作用。
介绍下3种python获取cookie的方法。
(1)借助handler
这个方法也是网上介绍最多的方法,但是使用起来比较麻烦
from http import cookiejar
from urllib import request
class Craw():
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'
def getCookies(self):
cookie = cookiejar.CookieJar()
handler = request.HTTPCookieProcessor(cookie)
opener = request.build_opener(handler)
response = opener.open(self.url)
cookieValue = ''
for item in cookie:
cookieValue += item.name + '=' + item.value + ';'
self.headers['Cookie'] = cookieValue
response = requests.get(url=self.url)
def getVerificationCode(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
class Crawler():
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方法,代码如下:
import requests
class Crawler():
def getCookie(self):
response = requests.get(self.url)
cookie_value = ''
for key,value in response.cookies.items():
cookie_value += key + '=' + value + ';'
self.headers['Cookie'] = cookie_value
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ python的界面是什么样的08/13
- ♥ python中的线程和协程有什么区别11/19
- ♥ 如何在python中获取列表的前几个元素08/14
- ♥ python如何实现哥德巴赫分解11/03
- ♥ python读取文件时出现空行的解决方法11/18
- ♥ 如何使用python库实现绘制3D图形?11/18
内容反馈