大家好,欢迎来到IT知识分享网。
一、程序介绍
个人博客
学校网课繁多,自己又没时间去守着手机枯燥的点击下一步。既然是枯燥无味又重复执行的事情,程序员面临这种问题,,,让他自动点击或者完成就显得明智得多,程序员的时间是用来学习的。
那么如何实现自动呢,python程序员都知道的一个WEB自动化工具,那就是selenium。对python没有接触或接触较少的同学,本篇最后也附带源码以便于大家使用。
提醒:本案例仅学术研究讨论,非法用途后果自负
二、程序搭建
- 驱动下载
查看自己浏览器的版本后前往官网下载驱动(本篇以Edge为例)
Edge浏览器的驱动地址为https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
在其中找到自己对应的浏览器驱动 - 创建项目
本案例开发工具选择pycharm,创建工程
- 加入浏览器驱动
将下载好的驱动加入项目
- 新建py文件
# @author xiaozhang # @create 2021/12/15 11:46 from selenium import webdriver import time from traceback import print_exc from pathlib import Path import requests import cv2 from selenium.common.exceptions import SessionNotCreatedException BASE_DIR = Path(__file__).parent class MainBody: def __init__(self,a): self.start_time = time.perf_counter() self.url = r"https://weiban.mycourse.cn/index.html#/course?projectId="+a+"&projectType=special&title=%E4%BA%92%E8%81%94%E7%BD%91%2B%E5%A4%A7%E5%AD%A6%E7%94%9F%E5%AE%89%E5%85%A8%E6%95%99%E8%82%B23" self.driver = self.get_driver() self.login = False self.course_p_percent = 1 def get_driver(self): driver = webdriver.Edge(str(BASE_DIR / "msedgedriver.exe")) driver.maximize_window() driver.get(self.url) return driver def get_chapters(self): css_selector_chapter = ".folder-list > .folder-item" chapters = [] while not chapters: if not self.login: time.sleep(10) self.driver.implicitly_wait(5) if "login" not in str(self.driver.current_url): self.driver.get(self.url) self.driver.implicitly_wait(5) chapters = self.driver.find_elements_by_css_selector(css_selector_chapter) return chapters def let_login(self): self.start_time = time.perf_counter() self.login = True progress_percent_pre = self.driver.find_element_by_css_selector(".progress-percent").text progress_percent = float(str(progress_percent_pre)[:-1]) self.course_p_percent = progress_percent / 80 if progress_percent < 80 else 1 if self.course_p_percent == 1: email_c = "课程已全部完成" else: email_c = "已开始学习。当前进度为{}".format(progress_percent_pre) print(email_c) def let_a_course_finished(self, course): course.find_element_by_css_selector("h3").click() # 进入该课程 self.driver.implicitly_wait(15) time.sleep(6) inner_frame = self.driver.find_element_by_css_selector("iframe.page-iframe") self.driver.switch_to.frame(inner_frame) time.sleep(5) inner_frame_body = self.driver.find_element_by_css_selector("body") self.driver.execute_script("finishWxCourse()", inner_frame_body) time.sleep(1) self.driver.switch_to.alert.accept() time.sleep(1) def exe(self, if_debug: bool = False): chapters = self.get_chapters() if not self.login: self.let_login() finished_chapters_amount = 0 for chapter in chapters: # 遍历所有章节 state = str(chapter.find_element_by_css_selector(".state").text) assert state finished, total = tuple(state.split('/', 2)) if finished == total and not if_debug: finished_chapters_amount += 1 continue # 这一章节刷完了 # 进入到某个章节中 chapter.find_element_by_css_selector("div.folder-extra > a.btn").click() self.driver.implicitly_wait(5) # 章节 > 课程 获取列表最上面的那节课 css_selector_course = ".course-list > li:nth-child(1)" course = self.driver.find_element_by_css_selector(css_selector_course) if not if_debug: if course.find_elements_by_css_selector("h3 > i"): # 最上面的课已经处于完成状态了,则返回 return False self.let_a_course_finished(course) return False if finished_chapters_amount == len(chapters): durant = "共用时:{:.2f}秒".format(time.perf_counter() - self.start_time) print(f'课程已全部完成。{
durant}') return True else: return False def start(self): finished = False while not finished: try: finished = self.exe() except KeyboardInterrupt: break except Exception as e: print(e) print_exc() time.sleep(10) if __name__ == '__main__': Headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36' } def GetTimeStamp(): return round(time.time()) TimeStamp = GetTimeStamp() print("正在获取登录二维码") LoginBarCodeApi = f"https://weiban.mycourse.cn/pharos/login/genBarCodeImageAndCacheUuid.do?timestamp={
TimeStamp}" data = requests.get(LoginBarCodeApi, headers=Headers).json()["data"] BarCodePayload = {
"barCodeCacheUserId": data["barCodeCacheUserId"]} BarCodeImageUrl = data["imagePath"] BarCodeImage = cv2.VideoCapture(BarCodeImageUrl).read()[1] print("使用微信扫码授权登录后关闭二维码窗口") cv2.imshow("scan", BarCodeImage) cv2.waitKey(0) TimeStamp = GetTimeStamp() BarCodeCheckApi = f"https://weiban.mycourse.cn/pharos/login/barCodeWebAutoLogin.do?timestamp={
TimeStamp}" data = requests.post(BarCodeCheckApi, headers=Headers, data=BarCodePayload).json() if (data["code"] != '0'): print("登录失败 请检查扫码情况") else: data = data["data"] tenantCode = data["tenantCode"] token = data["token"] userId = data["userId"] userProjectId = data["preUserProjectId"] TimeStamp = GetTimeStamp() GetInformationApi = f"https://weiban.mycourse.cn/pharos/my/getInfo.do?timestamp={
TimeStamp}" Payload = {
'userId': userId, 'tenantCode': tenantCode, 'token': token } data = requests.post(GetInformationApi, headers=Headers, data=Payload).json()["data"] Name = data["realName"] Number = data["studentNumber"] print("[{} {}]登录成功\n".format(Name, Number)) GetProjectIdApi = f"https://weiban.mycourse.cn/pharos/index/getStudyTask.do?timestamp={
TimeStamp}" dataP = requests.post(GetProjectIdApi,headers=Headers,data=Payload).json()["data"] Pid = dataP["userProjectId"] try: handle = MainBody(a=Pid) handle.start() except SessionNotCreatedException as e: print("浏览器驱动版本不匹配") except: print_exc() input("\n\n------------OVER-----------\n\n请敲击回车来结束程序:")
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/145363.html