Cookies

Python Cookie 读取和保存

#保存 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)

)利用cookie模拟网站登录

下面我们以我们学校的教育系统为例,利用cookie实现模拟登录,并将cookie信息保存到文本文件中,来感受一下cookie大法吧!

 

 

 1 import urllib
 2 import urllib2
 3 import cookielib
 4 
 5 filename = 'cookie.txt'
 6 \#声明一个MozillaCookieJar对象实例来保存cookie,之后写入文件
 7 cookie = cookielib.MozillaCookieJar(filename)
 8 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
 9 postdata = urllib.urlencode({
10             'stuid':'201200131012',
11             'pwd':'23342321'
12         })
13 \#登录教务系统的URL
14 loginUrl = 'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login'
15 \#模拟登录,并把cookie保存到变量
16 result = opener.open(loginUrl,postdata)
17 \#保存cookie到cookie.txt中
18 cookie.save(ignore_discard=True, ignore_expires=True)
19 \#利用cookie请求访问另一个网址,此网址是成绩查询网址
20 gradeUrl = 'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bkscjcx.curscopre'
21 \#请求访问成绩查询网址
22 result = opener.open(gradeUrl)
23 print result.read()

以上程序的原理如下

创建一个带有cookie的opener,在访问登录的URL时,将登录后的cookie保存下来,然后利用这个cookie来访问其他网址。

如登录之后才能查看的成绩查询呀,本学期课表呀等等网址,模拟登录就这么实现啦,是不是很酷炫?

posted @ 2018-09-07 16:55  3532  阅读(87)  评论(0编辑  收藏  举报