python利用本地保存cookies文件登陸調取api

#!/usr/bin/python #coding=utf-8 import urllib2,urllib import cookielib import json import calendarpython

cookie=cookielib.MozillaCookieJar()#聲明一個CookieJar對象實例來保存cookie cookie.load('/Users/momo/Downloads/cookies.txt',ignore_discard=False,ignore_expires=False) class Get_report(object): def init(self):json

pass
def get_days(self,y):
    monthRange = calendar.monthrange(y, m)####第一個元素是所查月份的第一天對應的是星期幾(0-6),第二個元素是這個月的天數
    return monthRange
def  get(self):
    url = 'https://hubble.******.com/deptReadRate/query.do?'
    data = {
        "tab": "readRate",
        "rStartTime": "2017-%s-%s 08:00:00" %(m,st),
        "rEndTime":   "2017-%s-%s 00:00:00" %(m,et),
        "deptName":   "運維組",
        "isRecord":   "true",
        "pathName":   "/alarm.do"
    }
    get_url = url + urllib.urlencode(data)
    try:
        response = urllib2.Request(get_url)
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
        result = urllib2.urlopen(response)
        cont = json.loads(result.read())
        d = json.dumps(data["rStartTime"]) + '  ' + json.dumps(cont['result']['data'][0]['directorCount'])   + '       ' + json.dumps(cont['result']['data'][0]['readCount']) + '     ' +  json.dumps(cont['result']['data'][0]['rate'])
        return d
    except:
        print 'wrong'

def main(y=2017,m=1): get_report = Get_report() month = get_report.get_days(y) print month global st,et for i in range(1, int(month[1]) + 1):cookie

st = i
    et = i + 1
    cont = get_report.get()
    print cont
    if cont:
        with open("/Users/momo/Downloads/bao.txt", 'a+') as f:
            f.write(cont + '\n')

if name=='main': for m in range(1, 2): if m < 10: '0{}'.format(m) main(2017,m)運維

相關文章
相關標籤/搜索