扣丁学堂Python培训简述Python Cookie读取和保存方法

本篇文章扣丁学堂Python培训小编给读者们分享一下Python Cookie读取和保存方法,文中有详细的代码列出供小伙伴们参考,对Python Cookie读取和保存方法感兴趣的小伙伴就随小编来了解一下吧。

扣丁学堂Python培训简述Python Cookie读取和保存方法_第1张图片

如下所示:

#保存 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和人工智能方面内容的小伙伴,请关注扣丁学堂Python培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供权威的Python开发环境搭建视频,Python培训后的前景无限,行业薪资和未来的发展会越来越好的,扣丁学堂老师精心推出的Python视频教程定能让你快速掌握Python从入门到精通开发实战技能。扣丁学堂Python技术交流群:279521237。

你可能感兴趣的:(扣丁学堂Python培训简述Python Cookie读取和保存方法)