#!/usr/bin/python
# -*- coding: utf- -*-
"""
Function: Used to demostrate how to use Python code to emulate login baidu main page: http://www.baidu.com/
Note: Before try to understand following code, firstly, please read the related articles:
()【整理】关于抓取网页,分析网页内容,模拟登陆网站的逻辑/流程和注意事项 http://www.crifan.com/summary_about_flow_process_of_fetch_webpage_simulate_login_website_and_some_notice/ () 【教程】手把手教你如何利用工具(IE9的F12)去分析模拟登陆网站(百度首页)的内部逻辑过程 http://www.crifan.com/use_ie9_f12_to_analysis_the_internal_logical_process_of_login_baidu_main_page_website/ () 【教程】模拟登陆网站 之 Python版 http://www.crifan.com/emulate_login_website_using_python Version: --
Author: Crifan
""" 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 '-'*; #------------------------------------------------------------------------------
# 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' : "",
#'u' : "",
#'safeflg' : "",
'staticpage' : staticpage, #http%3A%2F%2Fwww.baidu.com%2Fcache%2Fuser%2Fhtml%2Fjump.html
'loginType' : "",
'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();

使用python模拟登陆百度的更多相关文章

  1. 【教程】模拟登陆百度之Java代码版

    [背景] 之前已经写了教程,分析模拟登陆百度的逻辑: [教程]手把手教你如何利用工具(IE9的F12)去分析模拟登陆网站(百度首页)的内部逻辑过程 然后又去用不同的语言: Python的: [教程]模 ...

  2. 模拟登陆百度以及Selenium 的基本用法

    模拟登陆百度,需要依赖于selenium 模块,调用浏览器,执行python命令 先来说一下这个selenium模块啦...... 本文参考内容来自 Selenium官网 SeleniumPython ...

  3. Python模拟登陆新浪微博

    上篇介绍了新浪微博的登陆过程,这节使用Python编写一个模拟登陆的程序.讲解与程序如下: 1.主函数(WeiboMain.py): import urllib2 import cookielib i ...

  4. Python模拟登陆万能法-微博|知乎

    Python模拟登陆让不少人伤透脑筋,今天奉上一种万能登陆方法.你无须精通HTML,甚至也无须精通Python,但却能让你成功的进行模拟登陆.本文讲的是登陆所有网站的一种方法,并不局限于微博与知乎,仅 ...

  5. Python模拟登陆TAPD

    因为在wiki中未找到需要的数据,查询也很迷,打算用python登录tapd抓取所需项目下的wiki数据,方便查找. 2018-9-30 19:12:44 几步走 模拟登录tapd 抓取wiki页左侧 ...

  6. Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享

    Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享 支付宝十年账单上的数字有点吓人,但它统计的项目太多,只是想看看到底单纯在淘宝上支出了多少,于是写了段脚本,统计任意时间段淘宝订单的消费情况,看 ...

  7. Selenium模拟登陆百度贴吧

    Selenium模拟登陆百度贴吧 from selenium import webdriver from time import sleep from selenium.webdriver.commo ...

  8. python 模拟登陆,请求包含cookie信息

    需求: 1.通过GET方法,访问URL地址一,传入cookie参数 2.根据地址一返回的uuid,通过POST方法,传入cooki参数 实现思路: 1.理解http的GET和POST差别 (网上有很多 ...

  9. python模拟登陆之下载

    好长时间没有更新博客了,哈哈. 今天公司给了这么一个需求,现在我们需要去淘宝获取上一天的订单号,然后再根据订单号去另一个接口去获取订单详情,然后再给我展示到web! 中间涉及到的技术点有: 模拟登陆 ...

随机推荐

  1. Codeforces1110F Nearest Leaf dfs + 线段树 + 询问离线

    Codeforces1110F dfs + 线段树 + 询问离线 F. Nearest Leaf Description: Let's define the Eulerian traversal of ...

  2. 2.9-2.10 hive中常见查询

    一.查询语句 https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select 1.select语法 SELECT [ALL ...

  3. Flutter实战视频-移动电商-06.Dio基础_Get请求和动态组件协作

    博客地址: https://jspang.com/post/FlutterShop.html#toc-0ee 编写页面代码 创建动态组件HomePage,原来的代码是静态的我们这里就去掉就可以了. 然 ...

  4. WeFlow 简单使用教程

    一.前言 WeFlow 是什么?一个高效.强大.跨平台的前端开发工作流工具.(官网定义),下载那些你们都知道,我就不一 一介绍了.下面我说一下简单使用: 二.使用教程 首先,我们使用 WeFlow 是 ...

  5. 安装APK时SO库的选择策略

    此文已由作者尹彬彬授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 0X0 前言 在Android系统中,当我们安装apk文件的时候,lib目录下的so文件会被解压到app的原 ...

  6. ES6笔记总结

    常用命令 函数的rest参数和扩展 promise使用 module.exports和Es6 import/export的使用 function sum(x,y,z){ let total = 0; ...

  7. E20180712-hm

    directive n. 指令; <美>命令,训令,指令; 方针;

  8. CTP Release() 的注意问题

    测试时发现CThostFtdcMdSpi有个比较严重的问题,就是使用Release()退出清理对象时 会出现死机,并且频率很高,怎样解决? 答:请参考以下代码的释放顺序. template <c ...

  9. MyBatist庖丁解牛(五)

    很多时候我们在自己的每个service中没有中注入SqlSessionTemplate; 但是我们直接调用mapper接口方法就直接能够操作数据库 这个是为什么??下面开始解惑: Mybatis Sq ...

  10. P3809【模板】后缀排序

    传送门 深入理解了一波后缀数组,这东西真的很妙诶,自己推感觉完全不现实,看来只能靠背代码了 这段时间就多敲敲,把板子记熟吧 代码: #include<cstdio> #include< ...