selenium实现自动刷课示例

需求:
某大学远程教育自动刷课脚本,每20分钟刷一次。

  • 修改学习平台和超级鹰打码平台的用户名密码。
  • 安装对应的模块
    • pip install PIL 或者 pip install Pillow
    • pip install selenium
  • 下载chromderiver驱动,放到d:/chromedriver.exe.
    下载地址:http://chromedriver.storage.googleapis.com/index.html
    • 注意:电脑分辨率必须为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)

posted @ 2022-03-04 14:17  彬彬l  阅读(237)  评论(0)    收藏  举报