【Java简易爬虫】使用Htmlunit爬虫学校教务网课程表信息

使用WebClient和htmlunit实现简易爬虫

import com.gargoylesoftware.htmlunit.WebClient;

提供了public

P getPage(final String url)方法获得HtmlPage。

import com.gargoylesoftware.htmlunit.html.*;

包含了HtmlPage、HtmlForm、HtmlTextInput、HtmlPasswordInput、HtmlElement、DomElement等元素。

构造webclient对象

WebClient webClient= new WebClient();

无参默认是BrowserVersion.BEST_SUPPORTED,有参构造支持5种浏览器:

BrowserVersion.CHROME
BrowserVersion.EDGE
BrowserVersion.FIREFOX
BrowserVersion.FIREFOX_78
BrowserVersion.INTERNET_EXPLOER

使用webclient.getPage(String url)获得页面:

try {
   page = webClient.getPage(url);
} catch (IOException e) {
   e.printStackTrace();
}

利用webClient.getPage(url);方法,将其封装成一个getHtmlPage静态方法

private static class innerWebClient{
   private static final WebClient webClient = new WebClient();
}
public static HtmlPage getHtmlPage(String url){
   //调用此方法时加载WebClient
   WebClient webClient = innerWebClient.webClient;
   webClient.getOptions().setCssEnabled(false);
   //配置webClient
   webClient.getOptions().setCssEnabled(false);	//设置CSS是否生效
   webClient.getOptions().setJavaScriptEnabled(true);	//设置JS是否生效
   webClient.setAjaxController(new NicelyResynchronizingAjaxController());	//设置AJAX请求
   webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);	//设置是否抛出异常码
   webClient.getOptions().setThrowExceptionOnScriptError(false);	//设置是否抛出脚本错误
   webClient.waitForBackgroundJavaScript(3*1000);	//设置等待JS毫秒数
   webClient.getCookieManager().setCookiesEnabled(true);	//设置是否支持Cookie
   HtmlPage page = null;
   try {
       page = webClient.getPage(url);
   } catch (IOException e) {
       e.printStackTrace();
   }
   return page;
}

在教务官网学期课表页,拿到对应标签的ID
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SZUQdWi8-1636624187041)(C:\Users\CTC\Desktop\个人技术笔记\img\image-20211111172915897.png)]
登录教务官网页面:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dT0jj3LR-1636624187043)(C:\Users\CTC\Desktop\个人技术笔记\img\image-20211111171429061.png)]
静态解析课程信息方法:

//获取周次集合
public static ArrayList<Integer> getWeekCount(String weekAndSection){
   ArrayList<Integer> weekList = new ArrayList<>();
   int index = weekAndSection.indexOf("(周)");
   if(index == -1){
       return new ArrayList<>();
   }
   String subWeek  = weekAndSection.substring(0, index);     //1-3,5,15,18
   String[] weekArr = new String[10];
   int idx = subWeek.indexOf(",");     //1或3
   int num = 0,n = 0;
   while (subWeek.contains(",")){
       weekArr[num] = subWeek.substring(0,idx);    //第一个逗号前面的内容,给数组
       subWeek = subWeek.substring(idx+1);   //剩余内容
       n = subWeek.indexOf(",");
       idx = n;
       num++;
   }
   weekArr[num] = subWeek;
   for (String s : weekArr) {
       if(s!=null && !s.equals("")){
           if(s.contains("-")){
               int ix = s.indexOf("-");
               int begin = Integer.parseInt(s.substring(0,ix));
               int end = Integer.parseInt(s.substring(ix+1));
               for (int i = begin; i <= end; i++) {
                   weekList.add(i);
               }
           }else{
               weekList.add(Integer.parseInt(s));
           }
       }
   }
   return weekList;
}
//获取节次集合
public static ArrayList<Integer> getSectionCount(String weekAndSection){
   int begin = weekAndSection.indexOf("[") + 1;
   int end = weekAndSection.indexOf("节");
   String section = weekAndSection.substring(begin, end);
   int len = section.length();
   String first = section.substring(0,2);
   String last = section.substring(len-2,len);
   ArrayList<Integer> sectionList = new ArrayList<>();
   int firstInt = Integer.parseInt(first);
   int lastInt = Integer.parseInt(last);
   for (int i = firstInt; i <= lastInt; i++) {
       sectionList.add(i);
   }
   return sectionList;
}

开始解析课程信息

DomElement[][] domElements = new DomElement[7][6];  //7天,6个节次部分
String key = "";
//星期一~星期日:1-2~7-2
for (int i = 0;i < 7;i++){     //星期一到星期日
   for (int j = 0;j <= 5;j++){     //sectionIds[0]到sectionIds[5]
       if(j == 2){     //由于第5节为空,略过
           continue;
       }
       key = sectionIds[j] + "-" + (i+1) + "-2";
       if(page3.getElementById(key) == null){
           throw new NullPointerException("Key过期了!");
       }else{
           domElements[i][j] = page3.getElementById(key);
       }
       String course = domElements[i][j].asText();
       String temp[] = new String[10];
       int num = 0;
       int index;
       for (int g = 0; course.contains("---------------------"); g = g + index) {
           index = course.indexOf("---------------------");
           temp[num] = course.substring(0,index);
           course = course.substring(index+21);
           num++;
       }
       temp[num] = course;
       String[] courseInfo = new String[4];
       for (int k = 0;k < temp.length;k++) {
           if(temp[k] == null || temp[k].equals("") || temp[k].equals(" ")){
               continue;
           }
           if(temp[k].indexOf("\n") == 1){
               temp[k] = temp[k].substring(2);
           }
           ArrayList<Integer> weekList;
           ArrayList<Integer> sectionList;
           if(temp[k].contains("网络课")){
               temp[k] = temp[k].substring(0,temp[k].indexOf("\n"));
               courseInfo[0] = temp[k];
               weekList = null;
               sectionList = null;
           }else{
               int idx,cnum = 0;
               for(int h = 0; temp[k].contains("\n") && cnum <= 3;h = h+idx){
                   idx = temp[k].indexOf("\n");
                   courseInfo[cnum] = temp[k].substring(0,idx);
                   temp[k] = temp[k].substring(idx+1);
                   cnum++;
               }
               weekList = getWeekCount(courseInfo[2]);
               sectionList = getSectionCount(courseInfo[2]);
           }
           System.out.println("课程名===" + courseInfo[0]);
           System.out.println("教师名===" + courseInfo[1]);
           System.out.println("周次===" + weekList);
           System.out.println("节次===" + sectionList);
           System.out.println("地点===" + courseInfo[3]);
           System.out.println("星期" + (i+1));
       }
   }
}

输出效果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yTPDKTms-1636624187045)(C:\Users\CTC\Desktop\个人技术笔记\img\image-20211111173034258.png)]
基于Uni-App实现的课程表小程序:
在这里插入图片描述

  • 16
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
### 回答1: 好的,首先需要明确目标站的址和课程表页面的位置。然后,我们可以使用 Python 中的 requests 库向目标站发送请求并获取页面内容,再使用 BeautifulSoup 库解析页面内容并提取课程表信息,最后将信息写入 CSV 文件中。 以下是实现的代码: ```python import requests from bs4 import BeautifulSoup import csv # 目标站的址和课程表页面的位置 url = "http://example.com/schedule" schedule_page = "schedule.html" # 发送请求并获取页面内容 response = requests.get(url + "/" + schedule_page) html = response.content # 解析页面内容并提取课程表信息 soup = BeautifulSoup(html, 'html.parser') table = soup.find('table', {'class': 'schedule-table'}) rows = table.find_all('tr') # 将信息写入 CSV 文件中 with open('schedule.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) for row in rows: cols = row.find_all('td') cols = [col.text.strip() for col in cols] writer.writerow(cols) ``` 需要注意的是,代码中的址和课程表页面的位置需要根据实际情况进行修改。此外,还需要根据实际情况调整课程表表格的类名和 CSV 文件的列数等参数。 ### 回答2: 为了获取本人本学期的课程表,可以运用所学的爬虫技术来实现。首先,需要分析学生课表的HTML文件结构,确定需要提取的文本内容的位置和形式。 以样例的"学生课表.html"文件为例,可以使用BeautifulSoup库来解析HTML文件,然后通过查找相应的标签和属性来定位课程表的文本内容。查找课程表所在的标签和属性时,可以通过浏览器的开发者工具来查看HTML结构和元素的属性。 接下来,可以使用BeautifulSoup提供的方法,如find()、find_all()等来查找和提取课程表的文本内容,并将其保存到一个列表中。 最后,将提取到的课程表文本内容写入到CSV文件中。可以使用csv模块来创建和写入CSV文件。遍历课程表列表,将每一节课的信息作为一行写入CSV文件中的对应列。 具体代码示例如下: ```python import csv from bs4 import BeautifulSoup # 解析HTML文件 with open("学生课表.html", "r", encoding="utf-8") as f: soup = BeautifulSoup(f, "html.parser") # 定位课程表的父级标签 table = soup.find("table", attrs={"id": "courseTable"}) # 提取课程表文本内容 schedule = [] for tr in table.find_all("tr"): row = [] for td in tr.find_all("td"): row.append(td.get_text().strip()) schedule.append(row) # 写入CSV文件 with open("schedule.csv", "w", encoding="utf-8", newline="") as f: writer = csv.writer(f) writer.writerows(schedule) ``` 通过以上步骤,可以成功运用爬虫技术,获取本人本学期的课程表,并将其提取的文本内容存入到schedule.csv文件中。 ### 回答3: 为了运用爬虫技术获取本人本学期的课程表,并将提取的课程表文本内容存入schedule.csv文件中,我们需要以下步骤: 1.首先,使用爬虫技术,获取页上的学生课程表信息。可以使用Python中的第三方库,例如BeautifulSoup、Requests等来发送HTTP请求获取页内容,并使用HTML解析器对页进行解析。 2.接下来,我们需要分析学生课程表页的HTML结构,找到包含课程表信息HTML元素节点。可以通过查看页源代码或使用开发者工具来获取相关信息。 3.一旦找到了包含课程表信息HTML元素节点,就可以使用相关的HTML标签和属性,从页中提取所需的课程表文本内容。可以通过对HTML元素节点的层级结构、样式、属性等进行分析,使用合适的选择器定位到目标元素节点并提取其中的文本内容。 4.提取到课程表的文本内容后,我们可以使用Python中的CSV模块,创建一个名为schedule.csv的CSV文件,并将提取的课程表文本内容写入CSV文件中。可以使用CSV模块提供的方法来操作CSV文件,例如writerow()方法来写入一行数据。 5.最后,我们可以通过运行这段爬虫程序,自动获取本人本学期的课程表,并将提取的课程表文本内容存入schedule.csv文件中。在以后需要使用课程表数据时,可以直接读取CSV文件进行处理和分析。 总结起来,我们通过爬虫技术获取学生课程表的步骤包括发送HTTP请求获取页内容、解析页结构、提取目标文本内容、创建CSV文件并写入数据。这样就可以方便地获取本人本学期的课程表,并将其保存为CSV文件供以后使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Charte

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值