当前位置:
首页 > Python基础教程 >
-
使用python模拟登陆百度
使用python模拟登陆百度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
#!/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(); |
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式