python 模拟登陆园子

主要用到了python cookielib,urllib2,urllib这3个模块,python 不亏是具有 先天做 爬虫的特质,废话多说直接上代码

 1  #coding: utf-8 
 2 import sys
 3 import re
 4 import cookielib
 5 import urllib2
 6 import urllib
 7 
 8 class Login(object):
 9     def __init__(self):
10         self.name=self.pwd=self.operate=""
11         self.cj=cookielib.LWPCookieJar()
12         try:
13             self.cj.revert('p.cookie')
14         except Exception,e:
15             print e
16         self.opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
17         urllib2.install_opener(self.opener)
18 
19     def setinfo(self,username,pwd):
20         """设置登陆参数"""
21         self.name = username
22         self.pwd = pwd
23      
24 
25     def login(self):
26         """登陆cnblog"""
27         params={'tbUserName':self.name,
28                 'tbPassword':self.pwd,
29                 "__EVENTVALIDATION":"/wEdAAUyDI6H/s9f+ZALqNAA4PyUhI6Xi65hwcQ8/QoQCF8JIahXufbhIqPmwKf992GTkd0wq1PKp6+/1yNGng6H71Uxop4oRunf14dz2Zt2+QKDEIYpifFQj3yQiLk3eeHVQqcjiaAP",
30                 "__VIEWSTATE":"/wEPDwULLTE1MzYzODg2NzZkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQtjaGtSZW1lbWJlcm1QYDyKKI9af4b67Mzq2xFaL9Bt"}
31         print 'login......'
32         req=urllib2.Request(
33             'https://passport.cnblogs.com/login.aspx',
34             urllib.urlencode(params))
35         self.operate = self.opener.open(req)
36         if self.operate.geturl() == 'http://home.cnblogs.com':
37             print 'logged on successfully!'
38             self.cj.save("p.cookie") #保存cookies
39             print self.operate.url
40         else:
41             print 'login error.....'
42 
43 if __name__=='__main__':
44             L = Login()
45             L.setinfo("echosong",'****')
46             L.login()

 

 

posted @ 2013-12-22 12:25  EchoSong  阅读(1773)  评论(1编辑  收藏  举报