#!/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. HDOJ-1280

    前m大的数 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submi ...

  2. Identity Server 4 原理和实战(完结)_----选看 OAuth 2.0 简介(上)

    https://www.yuque.com/yuejiangliu/dotnet/cg95ni 代表资源所有者的凭据 授权 Authorization Grant 授权是一个代表着资源所有者权限的凭据 ...

  3. UVa 12333 Revenge of Fibonacci (字典树+大数)

    题意:给定一个长度小于40的序列,问你那是Fib数列的哪一项的前缀. 析:首先用大数把Fib数列的前100000-1项算出来,注意,一定不能是100000,要不然会WA的,然后每个数取前40位,不足4 ...

  4. React 从入门到进阶之路(六)

    之前的文章我们介绍了 React 表单事件 键盘事件 事件对象以及 React中 的 ref 获取 dom 节点 .双向数据绑定.接下来我们将介绍 React 表单详解 约束性和非约束性组件 inpu ...

  5. E20190114-hm

    anonymous adj. 匿名的; 无名的; 假名的; 没有特色的;

  6. Java文件输入输出

    public static void FileIO(String filename){ FileInputStream fis = null; try { fis = new FileInputStr ...

  7. 一款基于Bootstrap的js分页插件bootstrap-paginator使用实例

    Bootstrap Paginator是一款基于Bootstrap的js分页插件,功能很丰富.它提供了一系列的参数用来支持用户的定制,提供了公共的方法可随时获得插件状态的改变,以及事件来监听用户的动作 ...

  8. webstrom打开多个项目,webstrom常用快捷键

    1.webstrom打开多个项目 默认情况下一次只能打开一个项目,如果需要打开多个就按照下面的方法 File -> settings -> Directories -> Add Co ...

  9. spoj3105 MOD - Power Modulo Inverted(exbsgs)

    传送门 关于exbsgs是个什么东东可以去看看yyb大佬的博客->这里 //minamoto #include<iostream> #include<cstdio> #i ...

  10. java基础第二篇

    3.选择结构 a.if: 格式一: if(表达式1){ 表达式1为真才执行 } 格式二: if(表达式1){ 表达式1为真才执行 }else{ 表达式1位假才执行 } 格式三:判断工龄的范围,判断成绩 ...