• python2 登录带验证码的页面


    #!/usr/bin/python
    #-*- coding: utf-8 -*-

    import os,json;
    import urllib,urllib2;
    import cookielib;

    #获取cookie
    #声明一个CookieJar对象实例来保存cookie
    cookie = cookielib.CookieJar()
    #利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
    handler=urllib2.HTTPCookieProcessor(cookie)
    #通过handler来构建opener
    opener = urllib2.build_opener(handler)
    #此处的open方法同urllib2的urlopen方法,也可以传入request
    response = opener.open('web地址')
    #agent标识
    user_agent = {'User-Agent':'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}

    #登录
    while True:
        #获取验证码
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
        req_url='验证码地址'
        req=urllib2.Request(url=req_url,headers=user_agent)
        content=opener.open(req)
        
        
        imgpath="code.jpg"
        picture=content.read()
        with open(imgpath,"wb") as fp:
            fp.write(picture)
        
        #弹出验证码图片
        os.system("%s/%s"%(os.path.abspath('.'),imgpath))

        #输入验证码
        req_url='登录地址'
        code=raw_input("输入验证码:")
        if code == '':
            print("验证码不能为空")
            continue
        print(code)
        #验证
        req_data_dict={'username':'账号','password':'密码','code':code}
        req_data=urllib.urlencode(req_data_dict)
        req=urllib2.Request(url=req_url,data=req_data,headers=user_agent)
        content=opener.open(req)
        login=json.loads(content.read())
        if int(login[u'ok']) == 1:
            print(cookie)
            print('登录成功')
            break
        else:
            print(login)
            print("验证码错误")

    #参考以下资料

    http://python.jobbole.com/81344/

    https://www.cnblogs.com/xiaoxi-3-/p/7586072.html

    http://blog.csdn.net/liuyuan_jq/article/details/69524279

  • 相关阅读:
    二级菜单实现
    Python监控日志中经常访问的ip
    Python判断一个数是否为小数
    Python-读写文件
    python-字典
    Python实现屏蔽敏感词
    Python生成随机密码
    Python-列表和元组
    Jmeter命令行参数
    启动Jmeter时遇到的几种错误
  • 原文地址:https://www.cnblogs.com/cainiaoit/p/8202851.html
Copyright © 2020-2023  润新知