「乱搞」基于 selenium 与 xlwings 库的统计洛谷团队作业完成情况并输出到 excel
写在前面
学 JSON 后的一些瞎玩。
使用方法
首先需要安装 selenium
与 xlwings
库。
将下方两个文件放到同一文件夹中,按需修改 setting.json
后运行 main.py
,等待一段时间后将会弹出洛谷登录界面,登录后在命令行中按下回车后等待即可。
处理完成后将会在 settting.json
指定路径下创建 excel 表格并弹出。
注意
仅可统计团队中有备注者的成绩。
由于洛谷反爬机制较强,等待时间可能较长。
文件
setting.json
形式如下,按需修改其中参数即可。
JSON 有自我描述性真是太好了,解释都不用解释。
{
"team_id": "73524",
"training": [
{ "name":"贪心二分", "id":"459880" },
{ "name":"图论", "id":"454010"},
{ "name":"树状数组与线段树", "id":"453475"},
{ "name":"数论基础", "id":"451313"},
{ "name":"字符串", "id":"450450"},
{ "name":"DP进阶", "id":"448143"},
{ "name":"DP【祖传课件】", "id":"448138"}
],
"save_path": "C:\\Users\\Luckyblock233\\Desktop\\score.xlsx"
}
main.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import xlwings as xw
import time
import json
import random
driver = webdriver.Edge()
driver.get('https://www.luogu.com.cn/auth/login')
input()
setting_data = {}
with open('setting.json', 'r', -1, 'UTF-8') as f:
setting_data = json.loads(f.read())
sheet_data = {}
sheet_head = ["姓名", "总分"]
sheet_line_number = 1
#读取团队中所有人的备注:
driver.get('https://www.luogu.com.cn/team/' + setting_data['team_id'] + '#member')
time.sleep(10)
for user in driver.find_elements(By.CLASS_NAME, "message"):
sheet_data[str(user.text)] = [0, ]
#读取所有作业的排行榜并加入到表格数据中
for training in setting_data['training']:
driver.get('https://www.luogu.com.cn/training/' + training['id'] + '#rank')
sheet_head.append(training['name'])
sheet_line_number = sheet_line_number + 1
time.sleep(5 + random.randint(0, 10))
user_number = len(driver.find_elements(By.CLASS_NAME, "user"))
for i in range(1, user_number):
user = driver.find_elements(By.CSS_SELECTOR, "#app > div.main-container > main > div > div.card.padding-default > div > div:nth-child(2) > div.border.table > div.row-wrap > div:nth-child(" + str(i) + ") > span.user > span")
user = str(user[0].text)
score = driver.find_elements(By.CSS_SELECTOR, "#app > div.main-container > main > div > div.card.padding-default > div > div:nth-child(2) > div.border.table > div.row-wrap > div:nth-child(" + str(i) + ") > div:nth-child(3) > span")
score = int(score[0].text)
try:
sheet_data[user][0] = sheet_data[user][0] + score
sheet_data[user].append(score)
for line in sheet_data.values():
if len(line) != sheet_line_number:
line.append(0)
except:
print(user + 'isn\'t have a nickname!')
#在控制台中输出表格数据,可删除
for user, line in sheet_data.items():
print(user, end=": ")
for score in line:
print(score, end=" ")
print()
#将表格数据输出到 excel 中
app = xw.App(visible=True, add_book=False)
wb = app.books.add()
wb.sheets['sheet1'].range('A1').value = sheet_head
table = []
for user, scores in sheet_data.items():
table.append([user] + [s for s in scores])
wb.sheets['sheet1'].range('A2').expand('table').value = table
wb.save(str(setting_data['save_path']))
wb.close()
写在最后
构式。
作者@Luckyblock,转载请声明出处。