≡
  • 网络编程
  • 数据库
  • CMS技巧
  • 软件编程
  • PHP笔记
  • JavaScript
  • MySQL
位置:首页 > 网络编程 > Python

python 模拟登陆百度的简单示例

人气:479 时间:2018-10-18

这篇文章主要为大家详细介绍了python 模拟登陆百度的简单示例,具有一定的参考价值,可以用来参考一下。

对python这个高级语言感兴趣的小伙伴,下面一起跟随四海网的小编两巴掌来看看吧!

使用python模拟登陆百度


# @param 使用python模拟登陆百度
# @author 四海网|q1010.com 

#!/usr/bin/python
# -*- coding: utf-8 -*-
  
import re;
import cookielib;
import urllib;
import urllib2;
import optparse;
  
#------------------------------------------------------------------------------
# check all cookies in cookiesDict is exist in cookieJar or not
def checkAllCookiesExist(cookieNameList, cookieJar) :
    cookiesDict = {};
    for eachCookieName in cookieNameList :
        cookiesDict[eachCookieName] = False;
  
    allCookieFound = True;
    for cookie in cookieJar :
        if(cookie.name in cookiesDict) :
            cookiesDict[cookie.name] = True;
  
    for eachCookie in cookiesDict.keys() :
        if(not cookiesDict[eachCookie]) :
            allCookieFound = False;
            break;
  
    return allCookieFound;
  
#------------------------------------------------------------------------------
# just for print delimiter
def printDelimiter():
    print '-'*80;
  
#------------------------------------------------------------------------------
# main function to emulate login baidu
def emulateLoginBaidu():
    print "Function: Used to demostrate how to use Python code to emulate login baidu main page: http://www.baidu.com/";
    print "Usage: emulate_login_baidu_python.py -u yourBaiduUsername -p yourBaiduPassword";
    printDelimiter();
  
    # parse input parameters
    parser = optparse.OptionParser();
    parser.add_option("-u","--username",action="store",type="string",default='',dest="username",help="Your Baidu Username");
    parser.add_option("-p","--password",action="store",type="string",default='',dest="password",help="Your Baidu password");
    (options, args) = parser.parse_args();
    # export all options variables, then later variables can be used
    for i in dir(options):
        exec(i + " = options." + i);
  
    printDelimiter();
    print "[preparation] using cookieJar & HTTPCookieProcessor to automatically handle cookies";
    cj = cookielib.CookieJar();
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj));
    urllib2.install_opener(opener);
  
    printDelimiter();
    print "[step1] to get cookie BAIDUID";
    baiduMainUrl = "http://www.baidu.com/";
    resp = urllib2.urlopen(baiduMainUrl);
    #respInfo = resp.info();
    #print "respInfo=",respInfo;
    for index, cookie in enumerate(cj):
        print '[',index, ']',cookie;
  
    printDelimiter();
    print "[step2] to get token value";
    getapiUrl = "https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true";
    getapiResp = urllib2.urlopen(getapiUrl);
    #print "getapiResp=",getapiResp;
    getapiRespHtml = getapiResp.read();
    #print "getapiRespHtml=",getapiRespHtml;
    #bdPass.api.params.login_token='5ab690978812b0e7fbbe1bfc267b90b3';
    foundTokenVal = re.search("bdPass\.api\.params\.login_token='(?P<tokenVal>\w+)';", getapiRespHtml);
    if(foundTokenVal):
        tokenVal = foundTokenVal.group("tokenVal");
        print "tokenVal=",tokenVal;
  
        printDelimiter();
        print "[step3] emulate login baidu";
        staticpage = "http://www.baidu.com/cache/user/html/jump.html";
        baiduMainLoginUrl = "https://passport.baidu.com/v2/api/?login";
        postDict = {
            #'ppui_logintime': "",
            'charset'       : "utf-8",
            #'codestring'    : "",
            'token'         : tokenVal, #de3dbf1e8596642fa2ddf2921cd6257f
            'isPhone'       : "false",
            'index'         : "0",
            #'u'             : "",
            #'safeflg'       : "0",
            'staticpage'    : staticpage, #http%3A%2F%2Fwww.baidu.com%2Fcache%2Fuser%2Fhtml%2Fjump.html
            'loginType'     : "1",
            'tpl'           : "mn",
            'callback'      : "parent.bdPass.api.login._postCallback",
            'username'      : username,
            'password'      : password,
            #'verifycode'    : "",
            'mem_pass'      : "on",
        };
        postData = urllib.urlencode(postDict);
        # here will automatically encode values of parameters
        # such as:
        # encode http://www.baidu.com/cache/user/html/jump.html into http%3A%2F%2Fwww.baidu.com%2Fcache%2Fuser%2Fhtml%2Fjump.html
        #print "postData=",postData;
        req = urllib2.Request(baiduMainLoginUrl, postData);
        # in most case, for do POST request, the content-type, is application/x-www-form-urlencoded
        req.add_header('Content-Type', "application/x-www-form-urlencoded");
        resp = urllib2.urlopen(req);
        #for index, cookie in enumerate(cj):
        #    print '[',index, ']',cookie;
        cookiesToCheck = ['BDUSS', 'PTOKEN', 'STOKEN', 'SAVEUSERID'];
        loginBaiduOK = checkAllCookiesExist(cookiesToCheck, cj);
        if(loginBaiduOK):
            print "+++ Emulate login baidu is OK, ^_^";
        else:
            print "--- Failed to emulate login baidu !"
    else:
        print "Fail to extract token value from html=",getapiRespHtml;
  
if __name__=="__main__":
    emulateLoginBaidu();

# End www_512pic_com

本文来自:http://www.q1010.com/181/2290-0.html

注:关于python 模拟登陆百度的简单示例的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。

关键词:模拟登陆

您可能感兴趣的文章

  • PHP模拟登陆抓取页面内容示例
上一篇:Python解决nltk download出错:Error connecting to server: [Errno -2]
下一篇:Python 的 is 和 id入门实例
热门文章
  • Python 处理Cookie的菜鸟教程(一)Cookie库
  • python之pandas取dataframe特定行列的简单示例
  • Python解决json.dumps错误::‘utf8’ codec can‘t decode byte
  • Python通过pythony连接Hive执行Hql的脚本
  • Python 三种方法删除列表中重复元素的简单示例
  • python爬虫代码示例
  • Python 中英文标点转换示例
  • Python 不得不知的开源项目解析
  • Python urlencode编码和url拼接实现方法
  • python按中文拆分中英文混合字符串的简单示例
  • 最新文章
    • Python利用numpy三层神经网络的简单示例
    • pygame可视化幸运大转盘的简单示例
    • Python爬虫之爬取二手房信息的简单示例
    • Python之time库的简单示例
    • OpenCV灰度、高斯模糊、边缘检测的简单示例
    • Python安装Bs4及使用的简单示例
    • django自定义manage.py管理命令的简单示例
    • Python之matplotlib 向任意位置添加一个子图(axes)的简单示例
    • Python图像标签标注软件labelme分析的简单示例
    • python调用摄像头并拍照发邮箱的简单示例

四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。