Python Cookie详细教程
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
from urllib import request
from http import cookiejar
import ssl
# 导入ssl时关闭证书验证
ssl._create_default_https_context = ssl._create_unverified_context
#声明一个CookieJar对象实例来保存cookie
cookie = cookiejar.CookieJar()
#利用urllib库中的request的HTTPCookieProcessor对象来创建cookie处理器
handler=request.HTTPCookieProcessor(cookie)
#通过handler来构建opener
opener = request.build_opener(handler)
#此处的open方法同urllib的urlopen方法,也可以传入request
response = opener.open('https://www.baidu.com')
for item in cookie:
print('Name = '+item.name)
print('Value = '+item.value)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
Name = BAIDUID
Value = 7071852C0204A1DBEC3FDEEDD78C1CF6:FG=1
Name = BIDUPSID
Value = 7071852C0204A1DB064CB81A39538424
Name = PSTM
Value = 1597916281
Name = BD_NOT_HTTPS
Value = 1
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
from urllib import request
from http import cookiejar
import ssl
# 导入ssl时关闭证书验证
ssl._create_default_https_context = ssl._create_unverified_context
filename = 'cookie.txt'
cookie = cookiejar.LWPCookieJar(filename)
# 根据创建的cookie生成cookie的管理器
cookie_handle = request.HTTPCookieProcessor(cookie)
# 创建求求管理器,将上面3个管理器作为参数属性
# 有了opener,就可以替代urlopen来获取请求了
opener = request.build_opener(cookie_handle)
# 正常是用request.urlopen(),这里用opener.open()发起请求
response = opener.open('http://www.baidu.com')
# 保存cookie文件
cookie.save()
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
from urllib import request,parse
from http import cookiejar
# 创建cookiejar实例对象
cookie = cookiejar.LWPCookieJar()
# 读取已经保存的cookie文件
# 读取之后,就无需登录,直接访问主页即可
cookie.load('cookie.txt')
# 根据创建的cookie生成cookie的管理器
cookie_handle = request.HTTPCookieProcessor(cookie)
# 创建求求管理器,将上面3个管理器作为参数属性
# 有了opener,就可以替代urlopen来获取请求了
opener = request.build_opener(cookie_handle)
url = 'http://www.baidu.com'
# 那么此时的opener已经是包含了cookie信息的一个opener对象
res = opener.open(url)
html = res.read()
print(html)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
from urllib import request,parse
from http import cookiejar
filename = 'cookie.txt'
cookie = cookiejar.LWPCookieJar(filename)
# 根据创建的cookie生成cookie的管理器
cookie_handle = request.HTTPCookieProcessor(cookie)
opener = request.build_opener(cookie_handle)
def login():
# 登录url,需要从登录form的action属性中获取
url = 'url地址'
# 登录所需要的数据,数据为字典形式,
data = {
'username':'username',
'password':'password'
}
# 将数据解析成urlencode格式
data = parse.urlencode(data)
req = request.Request(url,data=data)
# 正常是用request.urlopen(),这里用opener.open()发起请求
response = opener.open(req)
# 保存cookie文件
cookie.save()