您的位置:首页 > 编程语言 > Python开发

如何利用python模拟登录(附源码)

2013-03-12 09:29 405 查看
1.关于python模拟登录,本质上是利用python脚本模拟浏览器登录,没有任何安全性问题

2.关于一些python知识,我就不多说,网上应该有很多,读者可以在网上找到很多

3.在这里附上我的人人登录,并讲一下实现步骤

#!/bin/python

#encoding=utf-8

import HTMLParser

import urlparse

import urllib

import urllib2

import cookielib

import string

import re

#登录界面的主页

hosturl="http://www.renren.com"

#这里是将用户名和密码等发送到的页面上,这里需要抓包(我的方法是打开chrome浏览器,打开到登录页面,打开“审查元素”,在里面的网络里面查到的)

posturl="http://www.renren.com/ajaxLogin/login?"

#生成cookie

cj=cookielib.LWPCookieJar()

cookie_support=urllib2.HTTPCookieProcessor(cj)

opener=urllib2.build_opener(cookie_support,urllib2.HTTPHandler)

urllib2.install_opener(opener)

#打开登录界面,获取cookie,并将该cookie保存下来

h=urllib2.urlopen(hosturl)

#构造头,这方法和上面获取posturl的方法是一样的

headers={

'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17'

,'Referer':'http://www.renren.com/SysHome.do'

}

#发送的数据,方法同上

postdata={

'captcha_type' :
'web_login',

'domain' :
'renren.com',

'email' :
'********', #用户名

'icode':
'',

'key_id':
'1',

'origURL':
'http://www.renren.com/home',

'password':
'*******************', #密码,这里是密文

'rkey':
'd0cf42c2d3d337f9e5d14083f2d52cb2'

}

#将数据进行编码

postdata=urllib.urlencode(postdata)

#构造一个请求消息

request=urllib2.Request(posturl,postdata,headers)

print "request:%s " %request

#发送一个请求消息

response=urllib2.urlopen(request)

text=response.read()

print "text:%s" %text

listvalue=text.split(",")

#获取到人人登录的主页,这里每个人也许会不一样,每个人需要根据自己的text的里面数据来解析

renrenhttp="http:"+listvalue[1].split(":")[2];

print "renrenhttp:%s" %renrenhttp

print urllib2.urlopen(renrenhttp).read()

4.接下来在附上自己苏大网关的python,多练几个来练手(这里就不添加注释了,注释同上)

#!/bin/python

#encoding=utf-8

import HTMLParser

import urlparse

import urllib2

import urllib

import cookielib

import string

import re

hosturl="http://wg.suda.edu.cn/index.aspx"

posturl="http://wg.suda.edu.cn/index.aspx"

cj=cookielib.LWPCookieJar()

cookie_support=urllib2.HTTPCookieProcessor(cj)

opener=urllib2.build_opener(cookie_support,urllib2.HTTPHandler)

urllib2.install_opener(opener)

h=urllib2.urlopen(hosturl)

headers={

"Referer":"http://wg.suda.edu.cn/index.aspx",

"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17"

}

postdata={

'TextBox1':'*******', #用户名,这里都是明文

'TextBox2':'*******', #密码

'nw':'RadioButton1',

'tm':'RadioButton6',

'Button1':'登录网关'

}

postdata=urllib.urlencode(postdata)

request=urllib2.Request(posturl,postdata,headers)

print "request:%s" %request

response=urllib2.urlopen(request)

text=response.read()

#print "text:%s" %text

5.推荐一些网站

我也是借鉴了网上的大神的文章才完成的,在这里推荐几个大神的文章

/article/8241043.html 这里是关于如何实现模拟登录的,我主要借鉴了这篇文章

http://docs.python.org/2/library/htmlparser.html 这里的文章是讲解如何解析html,便于实现自己的操作,如download 图片,这个在实现自己登录后,有很大的操作空间

每个人在转载是希望表明转载出处 ,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: