python3.3教程之模拟百度登陆

模拟百度的登陆,开发环境使用了python3。 

代码: 
  1. #-*-coding:utf-8-*-  
  2. '''  
  3. Created on 2014110日  
  4. @author: hhdys  
  5. @edit: www.jbxue.com  
  6. '''  
  7. import urllib.request,http.cookiejar,re  
  8. class Baidu:  
  9.     def login(self):  
  10.         cj = http.cookiejar.CookieJar()  
  11.         opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))  
  12.         opener.addheaders = [('User-agent''Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')]  
  13.         resp=opener.open('http://weigou.baidu.com/')  
  14.         for c in cj:  
  15.             print(c.name,"====",c.value)  
  16.         getapiUrl = "https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true"  
  17.         resp2=opener.open(getapiUrl)  
  18.         getapiRespHtml = resp2.read().decode("utf-8")  
  19.         foundTokenVal = re.search("bdPass\.api\.params\.login_token='(?P<tokenVal>\w+)';", getapiRespHtml)  
  20.         if foundTokenVal :  
  21.             tokenVal = foundTokenVal.group("tokenVal")  
  22.             print(tokenVal)  
  23.   
  24.             staticpage = "http://zhixin.baidu.com/Jump/index?module=onesite"  
  25.             baiduMainLoginUrl = "https://passport.baidu.com/v2/api/?login"  
  26.             postDict = {  
  27.                         'charset':"utf-8",  
  28.                         'token':tokenVal,  
  29.                         'isPhone':"false",  
  30.                         'index':"0",  
  31.                         'staticpage': staticpage,  
  32.                         'loginType'"1",  
  33.                         'tpl'"mn",  
  34.                         'callback'"parent.bd__pcbs__n1a3bg",  
  35.                         'username':"*****",   #用户名  
  36.                         'password':"*****",   #密码  
  37.                         'mem_pass':"on",  
  38.                         "apiver":"v3",  
  39.                         "logintype":"basicLogin"  
  40.                         }  
  41.             postData = urllib.parse.urlencode(postDict);  
  42.             postData = postData.encode('utf-8')  
  43.             resp3=opener.open(baiduMainLoginUrl,data=postData)  
  44.             for c in cj:  
  45.                 print(c.name,"="*6,c.value)  
  46.   
  47.       
  48. if __name__=="__main__":  
  49.     print("="*10,"开始")  
  50.     bd=Baidu()  
  51.     bd.login()  

你可能感兴趣的:(python3)