如何用python实现网页自动登录

Python013

如何用python实现网页自动登录,第1张

以登陆百度为例子,如下:

import urllib,urllib2,httplib,cookielib

def auto_login_hi(url,name,pwd):

url_hi="http://passport.baidu.com/?login"

#设置cookie

cookie=cookielib.CookieJar()

cj=urllib2.HTTPCookieProcessor(cookie)

#设置登录参数

postdata=urllib.urlencode({'username':name,'password':pwd})

#生成请求

request=urllib2.Request(url_hi,postdata)

#登录百度

opener=urllib2.build_opener(request,cj)

f=opener.open(request)

print f

#打开百度HI空间页面

hi_html=opener.open(url)

return hi_html

if __name__=='__main__':

name='name'

password='password'

url='yoururl'#例如:url='http://hi.baidu.com/cdkey51'

h=auto_login_hi(url,name,password)

print h.read()#h里面的内容便是登录后的页面内容

使用场景

在面对需要账号密码登录的网页时,可以通过定位输入框,使用send_keys

输入账号密码登录。

但是在面对某些无法通过页面直接登录的场景,比如需要微信或者软件扫码、验证码等才能进入页面的情况时,就可以通过cookie进行登录。

本文主要介绍通过记录上一次登录网页的cookie,在cookie生效期间直接绕过登录页面直接进入系统的登录方式。

登录页面后获取登录的cookie

读取之前存入的cookie

这样只要记录的cookie生效,那么就可以不用每次进入系统时都需要在登录页面登录啦~

用python登录,需要传入cookie,并在cookie里把账号密码传入进去就行

首先利用浏览器的开发工具:

(sss是我随便输入的账号密码)

得到请求网址为:网页链接

账号和密码的参数分别为:j_username和j_password。

利用cookielib模块就可以,代码:

import urllib,urllib2,cookielib

postdata=urllib.urlencode({

    'j_username':'xxxx',#你的账号

    'j_password':'xxxx' #你的密码

    })

url='http://ucenter.17zuoye.com/j_spring_security_check' #登录网址

ckfile='cookie.txt'创建一个文档来存储数据

cookie=cookielib.MozillaCookieJar(ckfile)

res=urllib2.HTTPCookieProcessor(cookie)

opener=urllib2.build_opener(res)

cont=opener.open(url,postdata)

cookie.save(ignore_discard=True,ignore_expires=True) #保存cookie到本地的cookie.txt

已经搞定了,你可以再添加一个url2,用opener.open(url2)来验证是否登录成功