python3.4.3模拟网站登陆并保存cookies

来源:赵克立博客 分类: Python 标签:Python发布时间:2015-11-25 05:21:05最后更新:2015-11-25 06:15:06浏览:2475
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2015-11-25 06:15:06
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

下面代码实现自动登陆网站并保存cookies下次直接打开就可以

import urllib.request
import urllib.parse
import http.cookiejar
import codecs
#请求头
headers = { 
	'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36',
	'Referer':'http://www.XXXXXX.com/'#,
        #'X-Requested-With':'XMLHttpRequest'
	}
#创建一个带cookie的网络打开器,后面的get post请求都使用这个打开
ckjar=http.cookiejar.MozillaCookieJar('cookies.txt')
try:
     """加载已存在的cookie,尝试此cookie是否还有效"""
     ckjar.load(ignore_discard=True, ignore_expires=True)
except Exception:
     """加载失败,说明从未登录过,需创建一个cookie kong 文件"""
     ckjar.save(ignore_discard=True, ignore_expires=True)
ckproc=urllib.request.HTTPCookieProcessor(ckjar)
opener=urllib.request.build_opener(ckproc)
#get取网页数据
def geturl(url,data={}):
        try:
            global headers
            global opener
            params=urllib.parse.urlencode(data)#.encode(encoding='UTF8')
            req=''
            if params=='' :
                   req=urllib.request.Request(url)
            else:
                   req=urllib.request.Request(url+'?%s'%(params)) 
            
            #设置headers
            for i in headers:
                req.add_header(i,headers[i])
            r=opener.open(req)
            ckjar.save(ignore_discard=True, ignore_expires=True)
            return r
        except urllib.error.HTTPError as e:
            print(e.code)
            print(e.read().decode("utf8"))
#get取网页数据
def posturl(url,data={}):
    try:
        global headers
        global opener
        params=urllib.parse.urlencode(data).encode(encoding='UTF8')
        req=urllib.request.Request(url,params,headers)
        r=opener.open(req)
        ckjar.save(ignore_discard=True, ignore_expires=True)
        return r  
    except urllib.error.HTTPError as e:
        print(e.code)
        print(e.read().decode("utf8"))
#登陆用的用户名密码
da={'username':'xxxxxxxx','password':'xxxxxxxx'}
#登陆地址
loginurl='http://www.XXXXXX.com/login'
#第一次get请求
r=geturl(loginurl,{})
#下面特征说明是登陆成功界面
islogin=s1.find('登录成功')
if islogin==-1 :    
        #下载验证码
        f2 = open( r'./downs/verify.png', 'wb' )
        #验证码地址
        urlSuning='http://www.XXXXXX.com/index.php'
        f2.write(geturl(urlSuning,{}).read())
        f2.close()
        da['verify']=input('请输入验证码:')
        #提交数据登陆
        r=posturl(loginurl,da)
        s1="%s"%r.read().decode()
        #下面特征说明登陆成功
        islogin=s1.find('登录成功')
#循环验证验证码
while islogin==-1 :
    r=geturl(loginurl,{})
    #下载验证码
    f2 = open( r"./downs/verify.png", "wb" )
    f2.write(geturl(urlSuning,{}).read())
    f2.close()
    print('验证码错误!')
    da['verify']=input('请输入验证码:')
    
    #提交数据登陆
    r=posturl(loginurl,da)
    s1="%s"%r.read().decode()
    #下面特征说明登陆成功
    islogin=s1.find('登录成功')
print('登陆成功')
input('请输入任意键继续...')

如果想使用浏览器的cookies的话就修改下面这段代码

ckjar=http.cookiejar.MozillaCookieJar(os.path.join('C:\Users\abcd\AppData\Roaming\Microsoft\Windows\Cookies', 'cookies.txt'))



微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python