院史學得好啊,哈哈哈哈哈哈哈

#!/usr/bin/python
# coding=utf-8
'''
powered by zhangbin
'''
import sys
import HTMLParser
import urlparse
import urllib
import urllib2
import cookielib
import string
import re
import time
import json
from BeautifulSoup import *
reload(sys)
sys.setdefaultencoding('utf-8')




hosturl = 'http://yszsjs2.cas.cn/answer.action'
posturl = 'http://yszsjs2.cas.cn/login.action'
refurl = 'http://yszsjs2.cas.cn/choose.action'


flag = 1






class ucas_freshmen(object):
    """class for retrieving the information of newest post """
    def __init__(self):
        self.username = ''
        self.pwd = ''
        self.code = ''


    def set_login_info(self, username = '@iie.ac.cn', pwd = ''):
        """ complete the base login information """
        self.username = username
        self.pwd = pwd




    def login(self):
        ''' login ucas_freshmen '''


        """ set cookies """
        cj = cookielib.LWPCookieJar()
        cookie_support = urllib2.HTTPCookieProcessor(cj)
        opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
        urllib2.install_opener(opener)


        headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
                   'Referer': hosturl}


        # first HTTP request without form data
        reqreq = urllib2.Request(posturl, '', headers)
        f = urllib2.urlopen(reqreq, timeout = 60)




        # get the safecode
        reqreq = urllib2.Request('http://yszsjs2.cas.cn/safe.code', '', headers)
        f = urllib2.urlopen(reqreq, timeout = 1000)
        outfile = open(r'/Users/bingoboy/Downloads/safecode.jpg','w+')
        filecontent =  f.read()


        outfile.write(filecontent)
        outfile.close()


        # input the safe code and send the data to the server
        self.code = raw_input('please input the code:')
        postData = {    'username' : self.username,
                        'pwd' : self.pwd,
                        'code' : self.code
        }
        postData = urllib.urlencode(postData)
        request = urllib2.Request(posturl, postData, headers)
        response = urllib2.urlopen(request, timeout = 600)


        #get the list of question and  store them into qid_list


        qid_list = []
        b_qid_url = '自定義'
        qid_url = ''
        for i in range(1, 8):
            qid_url = b_qid_url + str(i) + '.json'
            reqreq = urllib2.Request(qid_url, '', headers)
            f = urllib2.urlopen(reqreq, timeout = 1000)
            qid_list.append(getqid(f.read()))


        result_url = 'http://yszsjs2.cas.cn/answer.action'
        postData = {
            'button': '提交答案',
            'answer': '',
            'qid': ''
        }
        option = ['A', 'B', 'C', 'D']
        scorelist = [-1, -1, -1, -1]
        ans_for_each_30 = ['', '', '', '', '', '', '', '']
        tmp = ''
        for i in range(1, 31):
            tmp += 'options_' + str(i)
            postData[tmp] = 'A'
            tmp = ''




        for i in range(1, 8):
            postData['groupid'] = i
            for j in range(1, 31):
                for k in range(4):
                    postData['answer'] = get_ans_str(j, option[k])
                    postData['qid'] = qid_list[i - 1]
                    tmp += 'options_' + str(j)
                    postData[tmp] = option[k]
#                    print postData
                    tmp = ''


                    send = urllib.urlencode(postData)
                    request = urllib2.Request(result_url, send, headers)
                    response = urllib2.urlopen(request, timeout = 600)
                    response = response.read()
 #                   print k
                    scorelist[k] = get_i_score(i, response)
                    if k == 3:
                        ans_index = get_the_answer(scorelist)
#                        print 'the answer is', option[ans_index],
                        ans_for_each_30[i] += option[ans_index] + '_'
                        waiting(3)
            print 'the answer for the ', i, 'series is: ', ans_for_each_30[i]
            postData['answer'] = ans_for_each_30[i]
            send = urllib.urlencode(postData)
            request = urllib2.Request(result_url, send, headers)
            response = urllib2.urlopen(request, timeout = 600)
            waiting(3)




def get_the_answer(list):
    average = (list[0] + list[1] + list[2] + list[3]) / 4
    for i in range(4):
        if list[i] != average:
            return i


def get_i_score(index, fread):
    soup = BeautifulSoup(fread)
    ret =  soup.findAll('table', attrs = {'class': 'tk1_selected', 'qno': str(index)})
    return int (ret[0]['score'])


def getqid(fread):
    ret = ''
    json_r = json.loads(fread)
    for eachquestion in json_r:
        ret += str(eachquestion.get('id'))
        ret += '_'
    return ret


def get_ans_str(index, opt):
    ret = ''
    for i in range(30):
        if i != (index -1):
            ret += 'A_'
        else:
            ret += opt + '_'
    return ret




def waiting(num):
    count = 0
    while count < num:
        count += 1
        time.sleep(1)






def main():
    user_login = ucas_freshmen()
    user_login.set_login_info()
    count = 1
    while True:
        print 'start scrawling for the', count ,'\bth time.'
        count += 1
#        try:
        info = user_login.login()
#        except :
#            pass
        print '----------done and waiting for 60 seconds----------\n '
        waiting(60)




if __name__ == '__main__':
    main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章