由于最近在做一个关于班级的app,需要用到同学们的课表,想着通过解析html来获取。
于是,有了下面,借助jsoup包来解析html课表,生成每一周的课表。
下载jsoup包导入lib。
获取个人课表可以通过进入教务管理系统。“个人课表查询”点击右键,打开链接地址。
作者课表:grkbList
jsoup:jsoup下载地址
文档:中文文档资料
最后生成的结果
附上代码
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class schedule {
public static void main(String[] args) throws IOException {
String threeD[][][] = new String[19][5][7]; //定义19周一天5节课 一周7天,横着存
String arr[][] = new String[5][7];
File input = new File("文件名+路径");
Document doc = Jsoup.parse(input, "UTF-8");
Elements trs = doc.select("table").select("tr"); // 关键的一步 从html中把课表解析出来
// 显示全部一开始总的
for (int i = 2; i < trs.size(); i++) { // 由于我的html,i=0、1中的内容不关于课表,因此从2开始
Elements tds = trs.get(i).select("td");
for (int j = 1; j < tds.size(); j++) {
// String txt = tds.get(j).text();
arr[i - 2][j - 1] = tds.get(j).text();
System.out.print(arr[i - 2][j - 1] + " ");
}
System.out.println(" ");
}
System.out.println(" ");
for (int i = 0; i < 5; i++) { // 一天五节课
for (int j = 0; j < 7; j++) { // 一周七天
if ("".equals(arr[i][j]))
continue;
String[] sArray = arr[i][j].split("\\)");
String schname = ""; // 用于存储 切割的是(JD)之类的情况
for (String s : sArray) {
if ("".equals(s))
continue;
String strIndex = "周";
// 判断字符串A中字符串B方法:
if (s.indexOf(strIndex) == -1) { // 如果indexOf() 返回-1,表示不包含
schname = s;
continue;
} else {
if (!"".equals(schname)) {
s = schname + ")" + s; // 相加
schname = ""; // 置空
}
//利用正则表达式 , 匹配指定范围内的数字
String regEx = "[^0-9]";
// Pattern是一个正则表达式经编译后的表现模式
Pattern p = Pattern.compile(regEx);
// 一个Matcher对象是一个状态机器,它依据Pattern对象做为匹配模式对字符串展开匹配检查。
Matcher m = p.matcher(s);
// 将输入的字符串中非数字部分用空格取代并存入一个字符串
String string = m.replaceAll(" ").trim();
// 以空格为分割符在讲数字存入一个字符串数组中
String[] strArr = string.split(" ");
// 遍历数组转换数据类型输出
int index = 0; // 记录周数是第几个
int num[] = new int[2];
for (String s2 : strArr) {
if ("".equals(s2))
continue;
num[index++] = Integer.parseInt(s2);
if (index == 2)
break; // 跳出循环,确定周数范围
}
for (int t = num[0] - 1; t < num[1]; t++) { // 处理同一个时间段,按单双周两门课的问题
String strIndex1 = "单";
String strIndex2 = "双";
if ((s.indexOf(strIndex1) == -1) && (s.indexOf(strIndex2) == -1)) {
threeD[t][i][j] = s + ")";
} else if ((s.indexOf(strIndex1) != -1 && t % 2 == 0)
|| ((s.indexOf(strIndex2) != -1) && t % 2 == 1)) { // 如果indexOf() 返回-1,表示不包含
threeD[t][i][j] = s + ")";
}
}//end for
}
}
}
}
//显示每一周的课表
for (int z = 0; z < 18; z++) {
System.out.println("第" + (z + 1) + "周");
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 7; x++) {
System.out.print(threeD[z][y][x] + " --|-- ");
}
System.out.println("");
}
System.out.println("");
}
}
}