使用python模拟登陆百度

2022-04-10 0 423

使用python模拟登陆百度

#!/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();

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Python教程 使用python模拟登陆百度 http://www.20zxx.cn/375198/xuexijiaocheng/python.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务