*这里实现的是超星在线学习平台上课程的自动听取,虽然最终成功了但是由于并不了解网站后台的监控机制,还是乖乖肉身听课吧(逃
一、主体结构
由于实现的功能并不是十分复杂,这里只构造了一个AutoStudent类来完成自动听课,主要分为四个模块:
- 用户登录
- 选择课程
- 检测尚未完成的小节
- 自动听课
二、详细步骤
1.__init__()
首先创建一个类并定义初始化函数,在此函数中定义类变量self.browser用于访问页面,self.courseList用于存储之后检测到的尚未完成的小节,self.db用于访问数据库。
为了避免Chromedriver的元素定位问题,要将浏览器窗口最大化
self.browser.maximize_window()
之后建立与数据库的连接并检测是否已创建表StudentInfo
self.db = pymysql.connect(host='localhost', user='root', password='Zwp0816...', db='ChaoXingStuInfo')
self.cursor = self.db.cursor()
self.cursor.execute('CREATE TABLE IF NOT EXISTS StudentInfo(账号 VARCHAR(30), 密码 VARCHAR(20));')
self.db.commit()
至此,__init__()函数结束,以下为完整代码
from selenium import webdriver
import pymysql
class AutoStudent():
def __init__(self):
self.browser = webdriver.Chrome()
self.browser.maximize_window()
self.courseList = list()
self.db = pymysql.connect(host='localhost', user='root', password='*******', db='ChaoXingStuInfo')
self.cursor = self.db.cursor()
self.cursor.execute('CREATE TABLE IF NOT EXISTS StudentInfo(账号 VARCHAR(30), 密码 VARCHAR(20));')
self.db.commit()
2.login()
基本准备工作完成以后就可以用浏览器登录课程界面了。定义login()函数用以实现这个功能。
a).首先读取数据库中已存储的信息并显示,并让用户选择,如果不使用已有信息则提示输入,输入后询问是否将新的信息存入数据库
choice1 = ''
while True:
self.cursor.execute('SELECT * FROM StudentInfo')
result = self.cursor.fetchall()
if result:
print("\n===================数据库中已有学生信息===================")
for i in range(0, len(result)):
print(
"\n编号:" + str(i + 1) + "\t账号:" + result[i][0] + '\t密码:' + result[i][1])
print('\n')
choice1 = input("是否使用数据库中已有学生信息?(y/n) >>>")
if choice1 == 'y':
index = int(input("输入要使用的信息编号:")) - 1
try:
account = result[index][0]
password = result[index][1]
break
except:
print("输入错误!")
continue
else:
account = input("输入账号:")
password = input("输入密码:")
break
else:
account = input("输入账号:")
password = input("输入密码:")
break
if choice1 != 'y':
choice2 = input("\n是否将学生信息存入数据库?(y/n)")
if choice2 == 'y':
if choice1 != 'y':
sql = 'INSERT INTO StudentInfo VALUES(%s, %s)'
self.cursor.execute(sql, (account, password))
self.db.commit()
b).访问登录页面并定位账号输入框、密码输入框、验证码输入框、登录按钮这四个元素