Skip to content

Commit

Permalink
add NoticeInfoReq to get noticeInfo
Browse files Browse the repository at this point in the history
  • Loading branch information
SchwarzSail committed Jan 6, 2025
1 parent 7997b7c commit 3dbfb0e
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 9 deletions.
2 changes: 1 addition & 1 deletion jwch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ func TestGetExamRoomInfo(t *testing.T) {
}

func TestGetNoticesInfo(t *testing.T) {
_, err := stu.GetNoticeInfo()
_, err := stu.GetNoticeInfo(&NoticeInfoReq{PageNum: 2})
if err != nil {
t.Error(err)
}
Expand Down
4 changes: 4 additions & 0 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,7 @@ type NoticeInfo struct {
URL string // 通知链接
Date string // 通知日期
}

type NoticeInfoReq struct {
PageNum int // 获取第几页的数据,从 1 开始
}
39 changes: 31 additions & 8 deletions notice.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,33 +26,41 @@ import (
"github.com/west2-online/jwch/constants"
)

func (s *Student) GetNoticeInfo() (list []*NoticeInfo, err error) {
// 获取通知公告
// 1. 获取通知公告页面
func (s *Student) GetNoticeInfo(req *NoticeInfoReq) (list []*NoticeInfo, err error) {
// 获取通知公告页面的总页数
res, err := s.PostWithIdentifier(constants.NoticeInfoQueryURL, map[string]string{})
if err != nil {
return nil, err
}
// 2. 解析页面
list, err = parseNoticeInfo(res)
lastPageNum, err := getTotalPages(res)
if err != nil {
return nil, err
}
// 根据总页数计算 url
num := lastPageNum - req.PageNum + 1
url := fmt.Sprintf("https://jwch.fzu.edu.cn/jxtz/%d.htm", num)
doc, err := s.PostWithIdentifier(url, map[string]string{})
if err != nil {
return nil, err
}
list, err = parseNoticeInfo(doc)
if err != nil {
return nil, err
}
// 3. 返回结果
return list, nil
}

// 获取当前页面的所有数据信息
func parseNoticeInfo(doc *html.Node) ([]*NoticeInfo, error) {
// 解析通知公告页面
var list []*NoticeInfo

// 修正 XPath 表达式
sel := htmlquery.FindOne(doc, "//div[@class='box-gl clearfix']")
if sel == nil {
return nil, fmt.Errorf("cannot find the notice list")
}

// 查找所有的 <li> 元素
rows := htmlquery.Find(sel, ".//ul[@class='list-gl']/li")

for _, row := range rows {
Expand All @@ -74,9 +82,24 @@ func parseNoticeInfo(doc *html.Node) ([]*NoticeInfo, error) {
URL: url,
Date: date,
}

list = append(list, noticeInfo)
}

return list, nil
}

// 获取总页数
func getTotalPages(doc *html.Node) (int, error) {
totalPagesNode := htmlquery.FindOne(doc, "//span[@class='p_pages']//a[@href='jxtz/1.htm']")
if totalPagesNode == nil {
return 0, fmt.Errorf("未找到总页数")
}

totalPagesStr := htmlquery.InnerText(totalPagesNode)
var totalPages int
_, err := fmt.Sscanf(totalPagesStr, "%d", &totalPages)
if err != nil {
return 0, fmt.Errorf("解析总页数失败: %v", err)
}
return totalPages, nil
}

0 comments on commit 3dbfb0e

Please sign in to comment.