爬虫cookiejar模块使用,cookie管理

简介

有时候我们需要爬一些需要登录才能进入网页,这个时候就要用到cookie相关的一些模块来操作了

内置的http包里包含了cookie相关的一些模块,通过她们我们可以自动使用cookie

  • CookieJar
    • 管理储存cookie,像传出的http请求添加cookie
    • cookie存储在内存中,CookieJar示例回收后cookie将自动消失
  • FileCookieJar
    • 是CookieJar的字类
    • cookie保存在文件中
  • MozillaCookiejar
    • 是FileCookieJar的子类
    • 与moccilla浏览器兼容
  • LwpCookieJar
    • 是FileCookieJar的子类
    • 与libwww-perl标准兼容

案例

访问登录后的人人网主页

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from  urllib  import  request,parse
from  http  import  cookiejar
 
# 创建cookiejar实例对象
cookie  =  cookiejar.CookieJar()
 
# 根据创建的cookie生成cookie的管理器
cookie_handle  =  request.HTTPCookieProcessor(cookie)
 
# 创建http请求管理器
http_handle  =  request.HTTPHandler()
 
# 创建https管理器
https_handle  =  request.HTTPSHandler()
 
# 创建求求管理器,将上面3个管理器作为参数属性
# 有了opener,就可以替代urlopen来获取请求了
opener  =   request.build_opener(cookie_handle,http_handle,https_handle)
 
def  login():
     '''
     负责初次登录
     需要传递用户名和密码,来获取登录的cookie凭证
     '''
     # 登录url,需要从登录form的action属性中获取
     url  =  'http://www.renren.com/PLogin.do'
 
     # 登录所需要的数据,数据为字典形式,
     # 此键值需要从form扁担中对应的input的name属性中获取
     data  =  {
         'email' : '[email protected]' ,
         'password' : '123456'
     }
 
     # 将数据解析成urlencode格式
     data  =  parse.urlencode(data)
 
     req  =  request.Request(url,data = data)
 
     # 正常是用request.urlopen(),这里用opener.open()发起请求
     response  =  opener. open (req)
 
 
def  getHomePage():
     '''
     获取登录后的页面
     '''
 
     # 此url是登录后的链接地址
     url  =  'http://www.renren.com/965187997/profile'
 
     # 如果已经执行了上面的login函数,
     # 那么此时的opener已经是包含了cookie信息的一个opener对象
     res  =  opener. open (url)
 
     html  =  res.read().decode()
 
     with  open ( 'renren.html' , 'w' ) as f:
         f.write(html)
 
 
if  __name__  = =  '__main__' :
     '''
     依次执行上面两个函数
     '''
     login()
     getHomePage()

猜你喜欢

转载自blog.csdn.net/ren_ger/article/details/81057722