Python爬虫(四)——模拟登录imooc实战(利用cookie)

该实战是模拟登录慕课网,并且进入个人课程页面

一、思路

1、获取登录cookie,并保存。

2、进入个人课程页面

二、代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: xulinjie time:2017/11/1
import urllib2
import urllib
import cookielib

filename='cookie.txt'
cookie=cookielib.MozillaCookieJar(filename)
headler=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(headler)
value={"email":"xxxxxxx","password":"xxxxxxxx"}
data=urllib.urlencode(value)#转码
loginURL=r'http://www.imooc.com/'#因为登录页面和首页是在一起的
opener.open(loginURL,data)#模拟登录,并把cookie保存到变量
cookie.save(ignore_discard=True,ignore_expires=True)#保存cookie到cookie.txt中
myURL=r'http://www.imooc.com/u/6085318/courses'#个人课程的URL
result=opener.open(myURL).read()#读取个人课程页面
wfile=open(r'./1.html',r'wb')
wfile.write(result)
wfile.close()
print result

三、key的确定

每个网站的用户名和密码的name都是不一样的,所以需要审查元素来确定访问的网站的登录name
《Python爬虫(四)——模拟登录imooc实战(利用cookie)》

这样就实现的模拟登录慕课网,并扒下来个人课程的页面

下面是爬下来的本地页面

《Python爬虫(四)——模拟登录imooc实战(利用cookie)》

    原文作者:浅然_
    原文地址: https://blog.csdn.net/w_linux/article/details/78449388
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞