Python Cookie 读取和保存方法

yipeiwu_com5年前Python基础

如下所示:

#保存 cookie 到变量
import urllib.request
import http.cookiejar
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://flights.ctrip.com/')
 
for item in cookie:
	print('%s = %s' % (item.name,item.value))
 
 
#保存 cookie 到文件
import urllib.request
import http.cookiejar
cookie_file = 'E:/mypy/cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(cookie_file)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
#response = opener.open('http://flights.ctrip.com/')
request = urllib.request.Request('http://flights.ctrip.com/',headers={"Connection": "keep-alive"})
response = opener.open(request)
cookie.save(ignore_discard=True, ignore_expires=True)
 
for item in cookie:
	print('%s = %s' % (item.name,item.value))
 
 
#从文件中读取 cookie 访问
import urllib.request
import http.cookiejar
cookie_file = 'E:/mypy/cookie.txt'
cookie = http.cookiejar.MozillaCookieJar()
cookie.load(cookie_file, ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
request = urllib.request.Request('http://flights.ctrip.com/')
html = opener.open(request).read().decode('gbk')
print(html)

以上这篇Python Cookie 读取和保存方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

django 发送邮件和缓存的实现代码

发送邮件 概述:Django中内置了邮件发送功能,发送邮件需要使用SMTP服务,常用的免费服务器有:163、126、QQ 注册并登陆163邮箱 打开POP3/SMTP服务与I...

python使用sqlite3时游标使用方法

cursor就是一个Cursor对象,这个cursor是一个实现了迭代器(def__iter__())和生成器(yield)的MySQLdb对象,这个时候cursor中还没有数据,只有等...

python并发编程之多进程、多线程、异步和协程详解

最近学习python并发,于是对多进程、多线程、异步和协程做了个总结。 一、多线程 多线程就是允许一个进程内存在多个控制权,以便让多个函数同时处于激活状态,从而让多个函数的操作同时运行...

Python企业编码生成系统之系统主要函数设计详解

本文实例讲述了Python企业编码生成系统之系统主要函数设计。分享给大家供大家参考,具体如下: 一 主要函数功能描述 函数 功能...

python 利用turtle库绘制笑脸和哭脸的例子

python 利用turtle库绘制笑脸和哭脸的例子

我就废话不多说了,直接上代码吧! import turtle turtle.pensize(5) turtle.pencolor("yellow") turtle.fillcolor...