1. 程式人生 > 其它 >selenium實現自動刷課示例

selenium實現自動刷課示例

需求:
某大學遠端教育自動刷課指令碼,每20分鐘刷一次。

  • 修改學習平臺和超級鷹打碼平臺的使用者名稱密碼。
  • 安裝對應的模組
    • pip install PIL
    • pip install selenium
  • 下載chromderiver驅動,放到d:/chromedriver.exe.
    • 注意:電腦解析度必須為100%,不然無法呼叫.
  • 執行指令碼
from selenium import webdriver
from hashlib import md5
from PIL import Image
import time
import requests

class Chaojiying_Client(object):
    '''
    超級鷹呼叫類介面
    '''
    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 圖片位元組
        codetype: 題目型別 參考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:報錯題目的圖片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()

class Course_refush():
    '''
    刷某學習平臺的課程點選次數
    '''
    def __init__(self,chromdriver='d:/chromedriver.exe',codepath='./maincode.png',username='3101111111111035',password='111111',codeuser='username',codepass='password',codeid='99999'):
        self.codepath = codepath
        self.username = username
        self.password = password
        self.chromdriverpath = chromdriver
        self.codeuser = codeuser
        self.codepass = codepass
        self.codeid = codeid


    def analysis_code(self,imgPath, imgType):
        chaojiying = Chaojiying_Client(self.codeuser, self.codepass, self.codeid)  # 使用者中心>>軟體ID 生成一個替換 96001
        im = open(imgPath, 'rb').read()      # 本地圖片檔案路徑 來替換 a.jpg 有時WIN系統須要//
        return chaojiying.PostPic(im, imgType)['pic_str']

    def study_course(self,url):
        bro = webdriver.Chrome(executable_path=self.chromdriverpath)
        bro.get(url)

        #輸入使用者名稱密碼
        get_user_elem = bro.find_element_by_xpath('//*[@id="studentnum"]')
        get_user_elem.send_keys(self.username)
        get_pass_elem = bro.find_element_by_xpath('//*[@id="stupwd"]')
        get_pass_elem.send_keys(self.password)

        #解析驗證碼圖片地址
        bro.save_screenshot(self.codepath)
        code_img_tag = bro.find_element_by_xpath('// *[ @ id = "VCodeImg"]')
        location = code_img_tag.location
        size = code_img_tag.size
        rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']),
                  int(location['y'] + size['height']))  # 寫成我們需要擷取的位置座標
        i = Image.open(self.codepath)  # 開啟截圖
        frame4 = i.crop(rangle)  # 使用Image的crop函式,從截圖中再次擷取我們需要的區域
        frame4.save(self.codepath)

        #識別驗證碼
        code_result = self.analysis_code(self.codepath, 1902)

        #輸入驗證碼並記住密碼,點選登入
        get_code_elem = bro.find_element_by_xpath('//*[@id="vcode"]')
        get_code_elem.send_keys(code_result)
        get_retain_elem = bro.find_element_by_xpath('// *[ @ id = "ckbremeber"]')
        get_retain_elem.click()
        get_login_elem = bro.find_element_by_xpath('//*[@id="btnlogin"]')
        get_login_elem.click()

        #不關注公眾號
        get_nofollow_elem = bro.find_element_by_xpath('//*[@id="myModal"]/div[3]/a')
        get_nofollow_elem.click()

        homepage = bro.current_window_handle

        #獲取需要學習的課程連結
        get_curselink_elem = bro.find_elements_by_xpath('//*[@id="tab4"]/table/tbody//a[@href]')
        curse_links = []
        for curselink in get_curselink_elem:
            resultlink = curselink.get_attribute('href')
            if 'schoolwork' in resultlink:
                pass
            else:
                curse_links.append(resultlink)

        # 迴圈訪問需要學習的課程連結
        js = "window.open('{}','_blank');"
        for count in range(15):
            for getcurselink in curse_links:
                bro.execute_script(js.format(getcurselink))
                time.sleep(1)
            subhandles = bro.window_handles
            for newhandle in subhandles:
                if newhandle != homepage:
                    bro.switch_to.window(newhandle)
                    bro.close()
                    time.sleep(1)
            bro.switch_to_window(homepage)
            bro.minimize_window()
            time.sleep(1200)
        bro.quit()

if __name__ == '__main__':
    #打碼平臺
    codeuser = 'username'
    codepass = 'password'
    codeid = 'codeid'

    #學習平臺使用者密碼
    username = 'username'
    password = 'password'
    url = 'http://netstu.snnu.net/Login.aspx'
    curse_instance = Course_refush(username=username,password=password,codeuser=codeuser,codepass=codepass,codeid=codeid,chromdriver='d:/chromedriver.exe')
    curse_instance.study_course(url)