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

Python011

如何用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里面的内容便是登录后的页面内容

用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)来验证是否登录成功